问题在数场ArrayList和保存 [英] Problem In count field in Arraylist and save it
问题描述
好,我有这个价值一个ArrayList
well, I have an ArrayList with this values
ACU
ACU
ACU
ACU
ACY
ACY
AER
AER
AER
AGC
我需要得到每个单词的项目数,因此对于
I need to get the number of items of each Word, so for
- ACU我们将获得4,
- ACY我们将得到2,
- AER我们将获得3
- AGC我们将获得1。
通常一个字重复的数目是可变
所以另一次ACU可以是1,和ACY可以是100 ..
Generally the number a word is repeated is a variable so another time ACU could be 1,and ACY could be 100..
所以,我有一个类,以保持价值观whatWordAND的howmany
So., I have a class to keep the values "whatWord" AND "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)在以下code会导致错误,你知道值不存在,但我不知道该怎么办...
I am stuck here, because I know the part get(i+1) in the following code will cause error, You know value does not exist, but then I dont know what to do...
ArrayList<Word> arrayWords = new ArrayList<Word>();
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)
}
}
据推测,后为code我将获得
It is supposed that after the for code I will get
ACU 4,
ACY 2,
AER 3,
AGC 1.
首先,我试图做一个HashMap试试,请帮我这个code:
First I tried to do a HashMap try, please help me with this code:
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<Word> arrayWords = new ArrayList<Word>();
//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);
}
在此先感谢。
推荐答案
这可能是矫枉过正,你想要做什么。你可以更简单地创建一个地图,有三个字母的字符串作为关键和伯爵的价值。然后,只需遍历你的ArrayList
That might be overkill for what you want to do. You could more simply create a map that has the three-letter string as the key and the count as the value. Then just iterate over your ArrayList:
Map<String, Integer>wordCount = new HashMap<String, int>();
for(String seq : yourWordList){
// increment the count of the word by first obtaining its count,
// and then incrementing it. Paranthesis for clarity
wordCount.put(seq, (wordCount.get(seq)) + 1);
}
这篇关于问题在数场ArrayList和保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!