gpt4 book ai didi

java - HashMap if containsValue 无限循环问题

转载 作者:行者123 更新时间:2023-12-02 05:09:37 25 4
gpt4 key购买 nike

我正在尝试使用 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();


}

当我运行这段代码时,我遇到了无限循环,有人可以帮忙吗?我认为这是正确的想法,但可能是错误的执行,这是正确的方法吗?

提前致谢

最佳答案

问题是您在开始时创建 tempList,因此 tempList 将始终相同,并且 map.containsValue(tempList) 将始终返回 true

tempList 创建/声明移至 while 循环的开头:

while (map.size() < 10) {
List<String> tempList = new ArrayList<String>();
//...
}

关于java - HashMap if containsValue 无限循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27446120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com