Java卡牌游戏HashMap赋值异常:循环7次却无法得到7个元素
问题原因与解决方案
问题根源
- HashMap键唯一性限制:HashMap的核心规则是键(Key)不可重复,调用
put(key, value)时,若已存在相同Key,新值会直接覆盖旧值,不会新增条目。你循环7次随机生成type作为Key,很容易出现重复(比如多次选中"1"),每次重复都会覆盖之前的条目,最终元素数量自然少于7个。 - 随机索引范围错误:
r.nextInt(type.length-1)会导致type数组最后一个元素("r")永远无法被选中,同理colors数组的最后一个元素("yellow")也取不到,因为nextInt(n)生成的是0到n-1的整数,减1后最大索引少了一位。
解决方案
方案1:用ArrayList存储自定义Card对象(推荐)
这种方式贴合卡牌游戏逻辑,每张牌是独立对象,不会因类型重复被覆盖。
首先定义Card类:
class Card { private String type; private String color; public Card(String type, String color) { this.type = type; this.color = color; } @Override public String toString() { return type + "(" + color + ")"; } }
修改初始化代码:
static List<Card> p1 = new ArrayList<>(), p2 = new ArrayList<>(), p3 = new ArrayList<>(), u = new ArrayList<>(); public static void ini() { String[] colors = {"red", "green", "blue", "yellow"}; String[] type = {"1","2","3","4","5","6","7","8","9","+2","+4","w","r"}; Random r = new Random(); for (int i = 0; i < 7; i++) { // 修复随机索引范围,去掉减1,保证所有元素都能被选中 String cardType = type[r.nextInt(type.length)]; String cardColor = colors[r.nextInt(colors.length)]; p1.add(new Card(cardType, cardColor)); p2.add(new Card(cardType, cardColor)); p3.add(new Card(cardType, cardColor)); u.add(new Card(cardType, cardColor)); } } public static void main(String[] args) { ini(); System.out.println(p1); System.out.println(p2); System.out.println(p3); System.out.println(u); }
方案2:保留HashMap但确保Key唯一
如果必须用HashMap,可以给每个Key添加唯一标识,避免重复覆盖:
static HashMap<String, String> p1=new HashMap<>(),p2=new HashMap<>(),p3=new HashMap<>(),u=new HashMap<>(); public static void ini(){ String [] colors = {"red", "green", "blue", "yellow"}; String [] type = {"1","2","3","4","5","6","7","8","9","+2","+4","w","r"}; Random r = new Random(); for (int i = 0; i < 7; i++){ String cardType = type[r.nextInt(type.length)]; String cardColor = colors[r.nextInt(colors.length)]; // 用循环索引作为唯一后缀,保证Key不重复 p1.put(cardType + "_" + i, cardColor); p2.put(cardType + "_" + i, cardColor); p3.put(cardType + "_" + i, cardColor); u.put(cardType + "_" + i, cardColor); } } public static void main(String[] args){ ini(); System.out.println(p1); System.out.println(p2); System.out.println(p3); System.out.println(u); }
内容的提问来源于stack exchange,提问作者vardhiro
相关产品推荐
相关产品推荐

