java 比较同一数组的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/702513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:26:21  来源:igfitidea点击:

Compare elements of the same array

javaarrayscomparison

提问by Jessy

I have problem with comparing the value of array elements. e.g. I wanted to compare the value of index 0 and index 2, and index 1 to index 3 and so on. With the code below I suppose to get the result of numOfdifferentShape is 2 but I get 3. How can I solve this problem? :-(

我在比较数组元素的值时遇到问题。例如,我想比较索引 0 和索引 2 的值,以及索引 1 和索引 3 的值等等。使用下面的代码,我想得到 numOfdifferentShape 的结果是 2 但我得到 3。我该如何解决这个问题?:-(

int numOfdifferentShape=0;

myArray = {40.0, 40.0, 40.0, 40.0, 80.0, 40.0, 40.0, 40.0}

for (int a=0; int a<myArray.size(); a=a+2)
{
   for (int b=a+2; b<myArray.size; b=b+2)
   {
      if (!(myArray.get(a).equals(myArray.get(b) && myArray.get(a+1).equals(b+1)))
         numOfdifferentShape++;  
      break;
   }
}

回答by Michael Myers

There are several syntax errors in this code, but since TofuBeer has already pointed them out in the comments, I'll move on the the design and logic.

这段代码中有几个语法错误,但是由于 TofuBeer 已经在注释中指出了它们,我将继续设计和逻辑。

Going from the code, I'm assuming you don't have much experience with Java, and perhaps not with programming at all. So I'm going to go slowly here. I hope you aren't insulted by my explanations.

从代码来看,我假设您对 Java 没有太多经验,也许根本没有编程经验。所以我要慢慢来。我希望你没有被我的解释侮辱。

You say you are trying to find out how many of the objects which you are storing (as two ints) in your array are equal. To do this, you have to keep track of what unique objects you have already seen. Then you compare each object the list of unique objects and, if it doesn't match any of them, add it to the list. This is the basic algorithm.

你说你试图找出你在数组中存储的对象(作为两个整数)有多少是相等的。为此,您必须跟踪您已经看到的独特对象。然后将每个对象与唯一对象列表进行比较,如果不匹配其中任何一个,则将其添加到列表中。这是基本算法。

Now, have you noticed that I keep using the word "object" in my description? When that happens, it usually means you should be making a class. I would make a simple one like this, holding the two integers:

现在,您是否注意到我在描述中一直使用“对象”一词?发生这种情况时,通常意味着您应该创建一个类。我会做一个这样的简单的,持有两个整数:

class Box { // or whatever the objects are called
    private final int height;
    private final int width;
    public Box(int h, int w) {
        height = h;
        width = w;
    }
    public int getHeight() {
        return height;
    }
    public int getWidth() {
        return width;
    }
    @Override
    public boolean equals(Object other) {
        if (!(other instanceof Box))
            return false;
        Box b = (Box) other;
        return b.height == height && b.width == width;
    }
    @Override
    public int hashCode() {
        int hash = 7;
        hash = 97 * hash + this.height;
        hash = 97 * hash + this.width;
        return hash;
    }
}

Try to understand what each part of this code does (especially if this is actually your homework). Once you've got it, move on to the next part: doing the calculation that you were trying to do.

试着理解这段代码的每一部分做了什么(特别是如果这实际上是你的家庭作业)。一旦你掌握了它,就进入下一部分:做你想要做的计算。

Let's say you have an array of Boxes, like this:

假设您有一组 Boxes,如下所示:

Box[] boxes = {
    new Box(40, 40), new Box(40, 40), new Box(80, 40), new Box(40, 40)
};

(I can't tell if you're using an array or a list, so I'm just picking one to demonstrate.)

(我不知道你使用的是数组还是列表,所以我只是选择一个来演示。)

I already gave the algorithm for finding the number of unique items, so I'll show you how I would write it:

我已经给出了查找唯一项数量的算法,所以我将向您展示我将如何编写它:

List<Box> unique = new ArrayList<Box>();
for (Box box : boxes) {
    if (!unique.contains(box)) { // this is why I implemented equals() and hashCode()!
        unique.add(box);
    }
}
int numOfDifferentShape = unique.size();

This is much easier than trying to keep track of two ints for each object, plus it has the advantage that you can't get your array indices confused.

这比试图跟踪每个对象的两个整数要容易得多,而且它的优点是您不会混淆数组索引。

You could do this even more easily with a Set. It would look something like this:

您可以使用Set. 它看起来像这样:

Set<Box> boxSet = new HashSet<Box>();
for (Box b : boxes)
    boxSet.add(b);
int numOfDifferentShape = boxSet.size();

Note that these last two snippets use features from Java 1.5, so I don't know if you've run into them before.

请注意,最后两个片段使用了Java 1.5 的功能,所以我不知道您以前是否遇到过它们。

Does this make things clearer?

这是否使事情更清楚?

回答by Ferdinand Beyer

for (int i = 0; i < (myArray.size() - 2); ++i)
{
    if (myArray[i] != myArray[i + 2])
        ++numOfdifferentShapes;
}

回答by JeeBee

  1. You have two loops, your description suggests you only want one.
  2. You need to do bounds checking - do you want the n+2 to wrap to the start to the start of the array when it exceeds the length?
  1. 你有两个循环,你的描述表明你只想要一个。
  2. 您需要进行边界检查 - 当 n+2 超过长度时,您是否希望 n+2 包装到数组的开头?

回答by JeffH

I think you have a parentheses problem. You wrote:

我认为你有一个括号问题。你写了:

if (!(myArray.get(a).equals(myArray.get(b) && myArray.get(a+1).equals(b+1)))

when I think you mean:

当我认为你的意思是:

if (!(myArray.get(a).equals(myArray.get(b)) && myArray.get(a+1).equals(b+1))

Also, in the same line, instead of:

此外,在同一行中,而不是:

equals(b+1)

don't you mean

你不是说

myArray.get(b+1)

回答by TofuBeer

I have array list e.g. {40,40,80,20,40,40} I wanted to compare the elements. Even number of index (e.g. index 0, index 2, index 4 etc) represents Height of an object and Odd number of Index (e.g. index 1, index 3 ec) represent Width of an object. So, with the code above, Object 1 (index 0 and 1).

我有数组列表,例如 {40,40,80,20,40,40} 我想比较元素。索引的偶数(例如索引 0、索引 2、索引 4 等)表示对象的高度,索引的奇数(例如索引 1、索引 3 ec)表示对象的宽度。因此,使用上面的代码,对象 1(索引 0 和 1)。

Why not make an array of a Dimension class, something like this:

为什么不制作一个 Dimension 类的数组,如下所示:

public class Dimension
{
    private final int width;
    private final int height;

    public Dimension(final int w, 
                     final int h)
    {
        width  = w;
        height = h;
    }

    public int getWidth()
    {
        return (width);
    }

    public int getHeight()
    {
        return (height);
    }
}

then do a for loop something like this:

然后做一个像这样的for循环:

for(int i = 0; i < array.length; i += 2)
{
    final Dimension a;
    final Dimension b;

    a = array[i];
    b = array[i + 1];

    // compare a.getLength() to b.getLength() 
    // or 
    // compare a.getWidth() to b.getWidth() 
}

It is usually a bad idea to try and be "tricky" - saying even ones are with and odd ones are length is being tricky... bad idea IMO.

尝试变得“棘手”通常是一个坏主意 - 说偶数和奇怪的长度是棘手的...... IMO 坏主意。