我正在尝试使用hashmap和数组为一组6支球队创建一个夹具列表。我有一个6支球队的数组。每个团队必须互相玩两次。我正在从原始团队列表中随机删除每个团队并将它们添加到新列表中。这个新列表被添加到hashmap中。为了避免相同的夹具列表多次发生,我试图在将其添加到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();
}
当我运行这段代码的时候,我得到了一个无限循环,有人能帮忙吗?我认为这是正确的想法,但可能是错误的执行,这是正确的方法吗?
提前谢谢
问题是您在开始时创建的是temList
,因此temList
将始终相同,并且map.有值(temList)
将始终返回true
。
将temList
创建/声明移动到while循环的开头:
while (map.size() < 10) {
List<String> tempList = new ArrayList<String>();
//...
}
每次它是唯一的时,您都将temList
添加到您的地图中,但随后您调用temList. Clear()
并将其清除。
试试这个:
String random1,random2;
HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
Random myRandomizer = new Random();
List<String> testList = new ArrayList<String>();
testList.add("team1");
testList.add("team2");
testList.add("team3");
testList.add("team4");
testList.add("team5");
testList.add("team6");
int y = 0;
while(map.size() < 10) {
System.out.println("Match Day " + (y + 1));
List<String> tempList = new ArrayList<String>();
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");
}
if (!(map.containsValue(tempList))) {
y++;
map.put(y, (ArrayList<String>) tempList);
for (String s : tempList) {
testList.add(s);
}
} else if ((map.containsValue(tempList))) {
for (String s : tempList) {
testList.add(s);
}
}
}