我使用HashSet类型的HashMap值时遇到了一些问题。我宣布它如下:
HashMap<Double, HashSet<Double>> pre = new HashMap<Double, HashSet<Double>>();
在我的计划中,我正在生成毕达哥拉斯三元组(a,b,c)。我想将b添加到对应于键a的HashSet中,并将a添加到对应于键b的HashSet中。 有9个三元组,周长小于60:
3 4 5
6 8 10
9 12 15
12 16 20
15 20 25
5 12 13
10 24 26
7 24 25
15 8 17
因此在生成每个三元组后,我必须更新对应于a或b的HashSet。完成后,HashMap将如下所示:
1: 14:
2: 15: 8, 20
3: 4 16: 12
4: 3 17:
5: 12 18:
6: 8 19:
7: 24 20: 15
8: 6, 15 21:
9: 12 22:
10: 24 23:
11: 24: 7, 10
12: 5, 9, 16 25:
13: 26:
我该怎么做?任何帮助将不胜感激。
这是我的代码:
import java.io.*;
import java.util.*;
import java.math.*;
public class prob {
public static double P = 60.0;
public static double primCount = 0.0;
public static double tripCount = 0.0;
public static ArrayList<Triple> pt = new ArrayList<Triple>();
public static HashMap<Double, HashSet<Double>> pre = new HashMap<Double, HashSet<Double>>();
public static void main(String[] args) {
double start = System.currentTimeMillis();
double sum = 0.0;
for (int i = 0; i < 30; i++) {
pre.put((double)i, new HashSet<Double>(0));
}
p(3.0, 4.0, 5.0);
for (int i = 0; i < pre.size(); i++) {
System.out.println(pre.get(i));
}
double end = System.currentTimeMillis();
System.out.println("Time elapsed : " + (end - start) / 1000d + " seconds");
}
public static void p(double A, double B, double C) {
double a = A, b = B, c = C;
if (a + b + c > P) {
return;
}
primCount++;
double I = Math.floor(P / (a + b + c));
tripCount += I;
for (double i = 1; i <= I; i++) {
pt.add(new Triple(a * i, b * i, c * i));
HashSet<Double> copya = pre.get(a * i);
copya.add(b * i);
pre.remove(a * i);
pre.put(a * i, copya);
HashSet<Double> copyb = pre.get(b * i);
copyb.add(a * i);
pre.remove(b * i);
pre.put(b * i, copyb);
}
p(a - 2 * b + 2 * c, 2 * a - b + 2 * c, 2 * a - 2 * b + 3 * c);
p(a + 2 * b + 2 * c, 2 * a + b + 2 * c, 2 * a + 2 * b + 3 * c);
p(2 * b - a + 2 * c, b - 2 * a + 2 * c, 2 * b - 2 * a + 3 * c);
}
}
答案 0 :(得分:0)
你的密钥是双精度型的,但你得到的值是传递int,只需添加强制转换,它对我有用:
for (int i = 0; i < pre.size(); i++) {
System.out.println(pre.get((double)i));
}
或使用foreach使其不易出错:
for (Entry<Double, HashSet<Double>> entry : pre.entrySet()) {
System.out.println(entry.getKey() + " : " + pre.values());
}
此外,在向子集合添加值时,您无需覆盖它,只需直接使用它即可:
pt.add(new Triple(a * i, b * i, c * i));
pre.get(a * i).add(b * i);
pre.get(b * i).add(a * i);