java - 搜索对象数组

标签 java arrays search return

我正在尝试返回对象在对象数组中出现位置的索引。

public static int search(WordCount[] list,WordCount word, int n)
{
    int result = -1;
    int i=0;
    while (result < 0 && i < n)
    {
        if (word.equals(list[i]))
        {
            result = i;
            break;
        }
        i++;
    }
    return result;
}

WordCount[] 是对象数组。

wordWordCount 的实例。

nWordCount[]

中的对象数量

它运行,但未正确返回索引。感谢任何和所有的帮助。感谢您抽出时间。

类别

class WordCount
{
String word;
int count;
static boolean compareByWord;
public WordCount(String aWord)
{
    setWord(aWord);
    count = 1;
}
private void setWord(String theWord)
{
    word=theWord;
}
public void increment()
{
    count=+1;
}
public static void sortByWord()
{
    compareByWord = true;
}
public static void sortByCount()
{
    compareByWord = false;
}
public String toString()
{
    String result = String.format("%s (%d)",word, count);
    return result;
}
}

我怎么调用它......

for (int i=0;i<tokens.length;i++)
        {
            if (tokens[i].length()>0)
            {
                WordCount word = new WordCount(tokens[i]);
                int foundAt = search(wordList, word, n);
                if (foundAt >= 0)
                {
                    wordList[foundAt].increment();
                }
                else
                {
                    wordList[n]=word;
                    n++;
                }
            }
        }
    }

最佳答案

默认情况下,Object#equals仅返回两个引用是否引用同一个对象(与 == 运算符相同)。看看您正在做什么,您需要做的是在 WordCount 中创建一个方法来返回 word,例如:

public String getWord() {
    return word;
}

然后将搜索中的比较更改为:

if (word.equals(list[i]))

至:

if (word.getWord().equals(list[i].getWord()))

或者更改方法的签名以接受String,这样如果不需要,就不会创建新对象。

我不建议覆盖 WordCount 中的 equals ,以便它仅使用 word 来确定对象相等性,因为您还有其他字段。 (例如,只有当两个计数器的计数相同时,人们才会认为它们相等。)

执行此操作的另一种方法是使用 Map,它是一个关联容器。一个例子是这样的:

public static Map<String, WordCount> getCounts(String[] tokens) {
    Map<String, WordCount> map = new TreeMap<String, WordCount>();

    for(String t : tokens) {
        WordCount count = map.get(t);
        if(count == null) {
            count = new WordCount(t);
            map.put(t, count);
        }

        count.increment();
    }

    return map;
}

关于java - 搜索对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23096329/

相关文章:

java - Java 数组使用多少内存?

java - 简单的 Dagger 单元测试失败

java - SensorSimulator 在连接时抛出错误

php - 如何获取数组中键的位置

arrays - React 将字符串转换为 React 组件

python - 在文件夹中搜索包含子字符串的文件,python?

c - 从列表中搜索缓冲区以查找任何字符串的高效算法

search - 如何在 OpenSearchServer 中抓取但不索引网页?

java - Android:在通话期间显示消息

java - 从匿名内部类中突破方法