我尝试在for循环期间将数组元素相互比较。在我的情况下,我有一些重复的值,由于某些原因我无法删除,但我必须确定它们。
这是我拥有的,而且不适合我
int x;
int table[] = {1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9, 10};
for (x = 0; x <= table.length; x++) {
if (x == 0 || x + 1 < table.length) { //determine that element is not last
if (table[x] == table[x + 1]) { //determine if next element is the same
System.out.println(table[x] + "if x = x + 1");
}
//determine that element is equal to previous but not equal to next
if (table[x] != table[x + 1] && table[x] == table[x - 1]) {
System.out.println(table[x] + " if x != x + 1 but x = x - 1");
} else {
System.out.println(table[x]);
}
}
if (x + 1 == table.length) { //determine that element is last
System.out.println(table[x]);
}
}
答案 0 :(得分:0)
我在您的代码中看到了许多错误,
int x;
int table[] ={1,2,2,3,4,5,5,6,7,8,9,9,10};
for (x = 0; x < table.length; x++){ // <-- NOT <=
if (x + 1 < table.length){ //<-- what if the table only has one element?
if (table[x] == table[x + 1]) { // <-- Add a {, Java is hard to read without
// braces.
System.out.println(table[x] + "if x = x + 1");
} else if (x > 0 && table[x] == table[x - 1]) { // <-- check that x is
// greater then 0 before subtracting 1
System.out.println(table[x] + " if x != x + 1 but x = x - 1");
} else {
System.out.println(table[x]);
}
if (x + 1 == table.length){ //determine that element is last
System.out.println(table[x]);
}
}
}
答案 1 :(得分:0)
有许多方法可以使用JDK执行此操作。如果您使用Collections类,则此任务将更容易。例如,您可以按照以下步骤操作:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
另外,如果您愿意在guava或apache commons集合上添加依赖项,那么它们每个都有一个很好的Multimap实现,可以帮助您解决这个问题。
答案 2 :(得分:0)
然后您可以使用HasmMap。
如果你有一个数组,如[1,2,2,3,4,5,1,8,4]
它会给你一张地图:{[1 - &gt; (0,6)],[2 - > (1,2)],[3 - > (3)],[4 - > (4,8)],[5 - > (5)],[8 - > (7)]}
// mapping from number to indexes in the array where duplicates of number exists
HashMap<Integer, List<Integer>> duplicates = new HashMap<Integer, List<Integer>>();
for(int i=0; i < table.length; i++) {
int current = table[i];
List<Integer> dubList = duplicates.get(current);
if(dubList == null) {
dubList = new ArrayList();
duplicates.put(i, dubList);
}
dubList.add(current);
}
答案 3 :(得分:0)
您可以尝试以下代码
HashSet hs = new HashSet();
int table[] ={1,2,2,3,4,5,5,6,7,8,9,9,10};
for (int x = 0; x < table.length; x++)
{
hs.add(table[x]);
}
System.out.println(hs);
List<Integer> array = new ArrayList<Integer>(hs);
System.out.println(array);
现在你可以了解......