在java中比较相同数组的元素 [英] comparing elements of the same array in java
问题描述
我试图比较相同数组的元素。这意味着我想比较0元素与每个其他元素,1元素与每个其他元素等。问题是,它不能按预期工作。 。我做的是我有两个for循环从0到array.length-1 ..然后我有一个if语句如下:if(a [i]!= a [j + 1])
for(int i = 0; i for(int k = 0 ; k if(a [i]!= a [k + 1]){
System.out.println(a [i] +not与+ a [k + 1] +\\\
)相同;
}
}
}
首先,你需要循环到< a.length
,而不是 a.length - 1
。因为这是严格小于你需要包括上限。
所以,检查所有对元素你可以做:
for(int i = 0; i for(int k = 0; k if(a [i]!= a [k]){
// do stuff
}
}
}
但这会比较,例如 a [2]
c $ c> a [3] ,然后 a [3]
到 a [2]
。鉴于您正在检查!=
这似乎是浪费。
更好的方法是比较每个元素<$
到 for(int i = 0; i for(int k = i + 1; k if(a [i] != a [k]){
// do stuff
}
}
}
因此,如果你有索引[1 ... 5],比较将进行
- code> 1 - > 2
-
1 - > 3
-
1 - > 4
-
1 - > 5
-
2 - > 3
-
2 - > 4
-
2 - > 5
-
3 - > 4
-
3 - > 5
-
4 - > 5
因此,您看不到重复的对。想想一个人的圈子,所有人都需要彼此握手。
I am trying to compare elements of the same array. That means that i want to compare the 0 element with every other element, the 1 element with every other element and so on. The problem is that it is not working as intended. . What i do is I have two for loops that go from 0 to array.length-1.. Then i have an if statement that goes as follows: if(a[i]!=a[j+1])
for (int i = 0; i < a.length - 1; i++) {
for (int k = 0; k < a.length - 1; k++) {
if (a[i] != a[k + 1]) {
System.out.println(a[i] + " not the same with " + a[k + 1] + "\n");
}
}
}
First things first, you need to loop to < a.length
rather than a.length - 1
. As this is strictly less than you need to include the upper bound.
So, to check all pairs of elements you can do:
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
But this will compare, for example a[2]
to a[3]
and then a[3]
to a[2]
. Given that you are checking !=
this seems wasteful.
A better approach would be to compare each element i
to the rest of the array:
for (int i = 0; i < a.length; i++) {
for (int k = i + 1; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
So if you have the indices [1...5] the comparison would go
1 -> 2
1 -> 3
1 -> 4
1 -> 5
2 -> 3
2 -> 4
2 -> 5
3 -> 4
3 -> 5
4 -> 5
So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.
这篇关于在java中比较相同数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!