问题:在Arraylist中统计字段并保存
问题:在Arraylist中统计字段并保存
好的,我有一个包含以下值的ArrayList
ACU ACU ACU ACU ACY ACY AER AER AER AGC
我需要获取每个单词的项数,所以对于
- ACU,我们会得到4个项,
- ACY,我们会得到2个项,
- AER,我们将得到3个项,
- AGC,我们将得到1个项。
一般来说,单词重复的次数是一个变量,所以ACU下一次可能是1,ACY下一次可能是100..
那么,我有一个类用于保留“whatWord”和“howMany”值
public class Word { private String whatWord; private int howMany; public cVOPlaza(String whatWord, int howMany){ this.whatWord = whatWord; this.howMany= howMany; } public String getwhatWord() { return whatWord; } public void setwhatWord(String whatWord) { this.whatWord = whatWord; } public int gethowMany() { return howMany; } public void sethowMany(int howMany) { this.howMany = howMany; } }
我在这里卡住了,因为我知道下面代码中的get(i+1)部分会导致错误,你知道值不存在,但是我不知道该怎么办...
ArrayList arrayWords = new ArrayList(); int cuantos = 0; for (int i=0;i<OriginalList.size();i++) { String word1 = OriginalList.get(i).getWord(); String word2 = OriginalList.get(i+1).getWord(); if (word1.equals(word2)){ //this counter is bad here... //where do i increment it?? howMany++; Word a = new Word(word1,howMany); ///....DONT KNOW WHERE TO ADD THE OBJECT //to the list //arrayWords.add(a) } }
假设在for代码后,我将得到
ACU 4, ACY 2, AER 3, AGC 1.
首先我尝试做一个HashMap尝试,请帮助我完成这段代码:
HashMap table = new HashMap(); int value=0; String key=null; //INITIALIZE HASH??? LIKE THIS for (int i = 0; i < OriginalList.size; i++) { table.put(0,OriginalList.get(i).getWord()); } String word1=null; ArrayList arrayWords = new ArrayList(); //LOOP FOR SEARCHING for (int i = 0; i < OriginalList.size(); i++) { key = OriginalList.get(i).getWord(); if (table.containsKey(key)) { word1 = (String) table.get(key); value++; }else { word1 = (String) table.get(key); value=1 } //Add result?? Word a = new Word(word1,value); }
非常感谢。
admin 更改状态以发布 2023年5月21日