java - 返回数组中对象的所有位置的搜索方法 - Java

标签 java arrays object search

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

我当前的搜索方法如下所示:

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() 方法!

最佳答案

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

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

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

关于java - 返回数组中对象的所有位置的搜索方法 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47523023/

相关文章:

javascript - 迭代具有相同名称的对象属性

java - 无法在 Play Frame 工作应用程序中导入 com.google.firebase.FirebaseApplication

java - java中未排序数组列表中的最小元素

Java SwingWorker 现在更新模型

jquery - 无法在 JQuery 中使用动态数组名称

java - 分析从 Java 文件中读取的文本

javascript - json数据解析问题

java - MongoDB Java - 添加或更新数组

ios - 从数组中的值显示数组

c++ - 使 C++ 对象数组在 Python 中可迭代