【问题标题】:Search method that returns all the positions of an object in an array -Java返回数组中对象的所有位置的搜索方法-Java
【发布时间】:2017-11-28 02:32:53
【问题描述】:

Card 是一个对象,deck 是一个包含这些卡片的数组。我试图在牌组中找到给定卡片对象的所有位置,并将所有这些位置存储在一个新数组中,然后返回该新数组。

我目前的搜索方法是这样的:

public int[] search(Card c)
{
    int length = 0;
    for (int x = 0 ; x < deck.length ; x++) // look through an array
    {
        if (deck[x].equals(c)) // value found in the array
        {
        length++; //update length
        }
    }

    int[] temp = new int[length]; //create new int array with that length
    for (int x = 0 ; x < deck.length ; x++) // look through the old array again
    {
        if (deck[x].equals(c)) // value found in that array
        {
            for (int y = 0 ; y < temp.length ; y++) //go through new array
            {
               temp[y] = x+1; //add the position to new array
            }
        }
    }

    return temp;
}

我这样称呼它:

int[] pos = deck.search (Deck.deck[11]); //search for 11th card in deck
//display the position
System.out.println("The Card is in position:" + Arrays.toString(pos)); 

虽然此代码返回了一个适当长度的数组,但它会用该值最后一次出现的位置填充每个槽。 (注意:我没有使用 ArrayList)

更新:在取出更新 y 的 for 循环并改为使 y 成为每次卡片匹配时更新的变量(在第二个循环中)后,问题已得到解决。

感谢大家提到 equals() 方法!

【问题讨论】:

  • 尝试使用调试器
  • if (deck[x] == c) - 你的 Card 对象是否有一个被覆盖的 equals 方法?

标签: java arrays object search


【解决方案1】:

如果两个对象占用不同的内存位置但具有相同的内容(即红心皇后),则使用 == 比较对象可能很危险,因为使用 == 比较两个对象的内存位置。您应该重写 Card 中的 .equals() 方法,而是使用 if(deck[x].equals(c))...

Here 是一篇很好的文章,讨论了为什么 .equals 很重要

here是对象类中equals方法的文档

【讨论】:

  • 即使我使用了equals,它也给出了相同的输出:C
  • 你试过逐行运行调试器吗?有时,当我犯了一个粗心的错误时,实时查看变量更新可以帮助我看到我的问题。
  • 哦,好吧,我会做的 C:
猜你喜欢
  • 2014-10-03
  • 1970-01-01
  • 2018-08-09
  • 2014-07-26
  • 1970-01-01
  • 2018-10-21
  • 2011-06-06
  • 1970-01-01
  • 2015-07-06
相关资源
最近更新 更多