我正在尝试使用哈希图和数组为一组 6 支球队创建一个赛程列表。我有6个团队。每支球队必须互相比赛两次。我正在从原始团队列表中随机删除每个团队,并将它们添加到新列表中。此新列表将添加到哈希映射中。为了避免多次出现相同的灯具列表,我试图在将其添加到哈希图之前检查这个新列表,如果它已经存在,那么我不添加它。这是我到目前为止的代码:
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();
}
当我运行此代码时,我得到了一个无限循环,有人可以帮忙吗? 我认为这是正确的想法,但可能是错误的执行,这是正确的方法吗?
提前致谢
问题是你在一开始就创建了tempList
,所以tempList
总是相同的,map.containsValue(tempList)
总是返回true
。
在 while 循环的开头移动tempList
创建/声明:
while (map.size() < 10) {
List<String> tempList = new ArrayList<String>();
//...
}
唯一时,您都会将tempList
添加到地图中,但随后您调用tempList.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);
}
}
}