我正在尝试返回对象在对象数组中出现位置的索引。
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[]
是对象数组。
word
是 WordCount
的实例。
n
是 WordCount[]
它运行,但未正确返回索引。感谢任何和所有的帮助。感谢您抽出时间。
类别
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/