java HashMap如果包含值无限循环问题
我正在尝试使用hashmaps和数组为一组6个团队创建一个fixture列表。我有6支队伍。每个队必须相互比赛两次。我将从原始团队列表中随机删除每个团队,并将其添加到新列表中。此新列表将添加到hashmap中。为了避免同一个fixture列表出现多次,在将其添加到hashmap之前,我尝试检查这个新列表,如果它已经存在,那么我不会添加它。以下是我目前的代码:
List<String> testList = new ArrayList<String>();
List<String> tempList = new ArrayList<String>();
Random myRandomizer = new Random();
String random1,random2;
tempOrder = new ArrayList<ArrayList<String>>();
HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
testList.add("team1");
testList.add("team2");
testList.add("team3");
testList.add("team4");
testList.add("team5");
testList.add("team6");
int x = (testList.size()-1) * 2;
int y = 0;
while(map.size() < 10){
System.out.println("Match Day " + (y+1));
//while(tempOrder.size()<10){
// System.out.println("Match Day " + (tempOrder.size()+1));
while(testList.size()>0){
random1 = testList.get(myRandomizer.nextInt(testList.size()));
testList.remove(random1);
tempList.add(random1);
random2 = testList.get(myRandomizer.nextInt(testList.size()));
testList.remove(random2);
tempList.add(random2);
System.out.println( random1 + " V " + random2 + "\n");
}
//tempOrder.add((ArrayList<String>) tempList);
// add to hashmap
// check value exists
// if true add
// if not dont
if(!(map.containsValue(tempList))){
y++;
map.put(y, (ArrayList<String>) tempList);
for(String s: tempList){
testList.add(s);
}
tempList.clear();
//tempOrder.clear();
}
else if((map.containsValue(tempList))){
//System.out.println("issue");
//tempOrder.clear();
for(String s: tempList){
testList.add(s);
}
tempList.clear();
}
当我运行这段代码时,我得到了一个无限循环,有人能帮我吗?我认为这是正确的想法,但可能是错误的执行,这是正确的方法吗
提前谢谢
# 1 楼答案
问题是您在开始时创建了
tempList
,因此tempList
将始终保持不变,map.containsValue(tempList)
将始终返回true
在while循环开始时移动
tempList
创建/声明:# 2 楼答案
每次都将
tempList
添加到地图中,然后调用tempList.clear()
并将其删除试试这个: