可能重复:
How to find a duplicate of length 5 in a single array. Java
我试图查看数组中是否有任何重复项。
import java.util.Hashtable;
public class test {
static final int COUNT = 10;
static Hashtable<String, Integer> compareSet = new Hashtable<String, Integer>();
static String groupInteger = "";
static long arr[] = new long[5];
static int st = 1;
static int end = 56;
static double t1;
static double t2;
static int ctr = 0;
public static void main(String[] args) {
t1 = System.currentTimeMillis();
for (int n = 0; n < COUNT; n++) {
for (int i = 0; i < arr.length; i++) {
arr[i] = (long) ((Math.random() * (end - st + 1)) + st);
}
for (int i = 0; i < 5; i++) {
groupInteger += arr[i];
if (i % 5 == 0) {
System.out.println();
if (compareSet.containsKey(groupInteger)) {
ctr++;
System.out.println("duplicate found ");
int currentCount = compareSet.get(groupInteger);
compareSet.put(groupInteger, currentCount + 1);
} else {
compareSet.put(groupInteger, 1);
}
groupInteger = "";
}
System.out.print(arr[i]);
}
}
t2 = System.currentTimeMillis();
System.out.println();
System.out.println();
System.out.println("\t" + "Total run time is " + ((t2 - t1)) + "ms");
System.out.println(compareSet);
}
}
控制台:
12 23 8 44 23
28 13 39 49 53
37 40 16 53 48
6 45 14 52 20
32 4 41 10 38
38 29 25 21 13
16 34 45 26 11
22 33 54 21 10
40 34 53 37 50
20 26 48 32 51
我希望能够检查是否有重复的行。 我似乎无法使用这个代码来正常工作。 如果你看到了什么,请告诉我!谢谢
答案 0 :(得分:1)
如果您想查找“任何”重复项,那么您正在使用不适当的类 使用HashSet&lt; String&gt;
你的代码完全是错误的。 if-then部分必须在for之后,而不是if。
HashSet<String> compareSet = new HashSet<String> ();
...
groupInteger.empty ();
for (int i = 0; i < 5; i++) {
groupInteger += arr[i] + " ";
}
System.out.println(groupInteger);
if (compareSet.contains(groupInteger)) {
System.out.println("duplicate found ");
} else {
compareSet.add(groupInteger);
}
如果你想“重复”重复,我会使用HashMap
HashMap<String, Integer> compareSet = new HashMapt<String, Integer> ();
...
Integer act = compareSet.get(groupInteger);
if (act != null) {
System.out.println("duplicate found ");
compareSet.put(groupInteger, act + 1);
} else {
compareSet.put(groupInteger, 1);
}