在java中比较同一数组的元素 [英] comparing elements of the same array in java

查看:26
本文介绍了在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. 1 ->2
  2. 1 ->3
  3. 1 ->4
  4. 1 ->5
  5. 2 ->3
  6. 2 ->4
  7. 2 ->5
  8. 3 ->4
  9. 3 ->5
  10. 4 ->5
  1. 1 -> 2
  2. 1 -> 3
  3. 1 -> 4
  4. 1 -> 5
  5. 2 -> 3
  6. 2 -> 4
  7. 2 -> 5
  8. 3 -> 4
  9. 3 -> 5
  10. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆