Java 如何在对象的arraylist中搜索字符串

Java 如何在对象的arraylist中搜索字符串,java,arraylist,Java,Arraylist,我正在做一项任务,我必须在课文中数数单词。我已经创建了一个ArrayList,其中包含Wordisntances。当我扫描文本时,如果列表中不存在单词,我只需要在ArrayList中添加一个单词。如果它存在,我将使用方法.increasNumber()增加该值。我该怎么做 public ArrayList<Word> list = new ArrayList<Word>(); public void readBook(String fileName) throws Ex

我正在做一项任务,我必须在课文中数数单词。我已经创建了一个
ArrayList
,其中包含
Word
isntances。当我扫描文本时,如果列表中不存在单词,我只需要在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));
    }
}

不要使用
列表
,使用
映射
,其中关键字是您的单词,值是出现的次数

Map<String,Integer> map = new HashMap<>();
Integer count = map.get(word);
if (count == null) {
  map.put(word, 1);
} else {
  map.put(word, count+1);
}
Map Map=newhashmap();
整数计数=map.get(word);
如果(计数=null){
地图放置(单词1);
}否则{
map.put(单词,计数+1);
}

编辑:我误读了你的作品,@gonzo的评论是对的;)

您应该重新编写
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);
    }
}
List words=new ArrayList();
私有void addWord(字符串字){
单词w=新词(单词);
int i=单词索引of(w);
如果(i>=0){
words.get(i).increaseNumber();
}否则{
加上(w);
}
}

为了实现这一点,您还需要重写
Word#equals
hashCode
以仅基于内部内容(即
word1.equals(word2)
如果
word1
word2
都基于相同的字符串,则应返回true).

您的
列表
中充满了
Word
对象,您正在检查
列表
是否包含
字符串
对象。我们可以看看您的
Word
类吗?
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);
    }
}