2015-10-16 117 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都是基於相同的字符串)。