2015-10-16 98 views
-3

我正在处理一个任务,我必须在文本中计算单词。我创建了一个包含Word实例的ArrayList<Word>。当我扫描文本时,如果它已经不在列表中,我只能向ArrayList添加一个单词。如果存在,我将用方法.increasNumber()增加值。我该怎么做呢?如何在字符串中搜索对象的数组列表

public ArrayList<Word> list = new ArrayList<Word>(); 

public void readBook(String fileName) throws Exception { 
    String fileRead = fileName; 
    Scanner file = new Scanner(new File(fileRead)); 
    while(file.hasNextLine()) { 
     addWord(file.nextLine()); 
    } 
} 

private void addWord(String word) { 
    if (list.contains(word)) { 
     word.increasNumber); 
    } else { 
     list.add(new Word(word)); 
    } 
} 

这里是我的Word类:

public class Word { 
    String text; 
    int count = 0; 

    public Word(String text) { 
     this.text = text; 
    } 

    public String toString() { 
     return text; 
    } 

    public int getNumber() { 
     return count; 
    } 

    public void increasNumber() { 
     count++; 
    } 
} 
+1

你的'list'中充满了'Word'对象,你正在检查'list'是否包含'String'对象。 – gonzo

+0

我们可以看到你的'Word'类吗? – gonzo

回答

0

不要使用List,使用Map<String,Integer>其中关键是你的字和值出现次数的数量。

Map<String,Integer> map = new HashMap<>(); 
Integer count = map.get(word); 
if (count == null) { 
    map.put(word, 1); 
} else { 
    map.put(word, count+1); 
} 

编辑:我误解你的OP,@ Gonzo的评论是正确的;)

0

你应该重新写addWord()方法:

List<Word> words = new ArrayList<>(); 

private void addWord(String word) { 
    Word w = new Word(word); 
    int i = words.indexOf(w); 
    if (i >= 0) { 
     words.get(i).increaseNumber(); 
    } else { 
     words.add(w); 
    } 
} 

为了使这项工作还需要覆盖Word#equalshashCode仅基于内部内容(即,word1.equals(word2)应该返回true,如果word1word2都是基于相同的字符串)。