comparing elements of the same array in java(在java中比较同一数组的元素)
问题描述
我正在尝试比较同一数组的元素.这意味着我想将 0 元素与其他所有元素进行比较,将 1 元素与其他所有元素进行比较,依此类推.问题是它没有按预期工作..我所做的是我有两个从 0 到 array.length-1 的 for 循环.然后我有一个 if 语句,如下所示: if(a[i]!=a[j+1])
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] + "
");
}
}
}
推荐答案
首先,你需要循环到 a.length
而不是 a.length - 1
.因为这严格小于您需要包含的上限.
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
}
}
}
但这会比较,例如 a[2]
到 a[3]
然后 a[3]
到 一个[2]代码>.鉴于您正在检查
!=
这似乎很浪费.
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.
更好的方法是将每个元素 i
与 数组的其余部分进行比较:
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
}
}
}
因此,如果您有索引 [1...5],则比较会进行
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
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中比较同一数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在java中比较同一数组的元素


- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 转换 ldap 日期 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01