【发布时间】:2014-12-12 14:48:04
【问题描述】:
我正在尝试使用哈希图和数组为一组 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();
}
当我运行这段代码时,我遇到了一个无限循环,有人可以帮忙吗?我认为这是正确的想法,但可能是错误的执行,这是正确的方法吗?
提前致谢
【问题讨论】:
-
请格式化您的代码 - 没有缩进会更难阅读。理想情况下,您应该将其转换为 short 但完整的程序来演示问题。我怀疑你可以缩短你已经得到的东西,你绝对可以去除随机性并将其包装在一个完整的程序中
标签: java random arraylist hashmap infinite-loop