Assuming you did not mean set as a java.util.Set check out the following:
/** Uses an ArrayList to contain a collection
* of String words.
*/
public class WordList extends java.util.ArrayList{
/** Constructs an empty Wordset.
*/
public WordList(){
super();
}
/** Constructs a WordList from an array of
* word string objects.
*/
public WordList(String[] words){
super();
for (int i = 0; i < words.length;i++){
add(words[i]);
}
}
/** Counts the number of times the input string matches
* exactly each word in the ArrayList
*/
public int getOccurances(String word){
int occurances = 0;
java.util.Iterator iterator = iterator();
while (iterator.hasNext()){
String nextWord = (String)iterator.next();
if (nextWord.equals(word)) occurances++;
}
return occurances;
}
/** Determines if the input string matches
* at least one word in the ArrayList.
*/
public boolean occurs(String word){
return contains(word);
}
/** Returns the String array of words.
*/
public String[] getWords(){
String[] strings = new String[size()];
for (int i = 0;i < size(); i++){
strings[i] = (String)get(i);
}
return strings;
}
/** Returns the array of words as a List.
*/
public java.util.List getList(){
return (java.util.List)this;
}
/** Sorts the underlying an array of word
* string objects using the static
* Arrays.sort(String[]) method.
*/
public void sort(){
java.util.Arrays.sort(getWords());
}
}
The following class tests the feature you wanted.
public class Test{
public static void main(String[] args){
new Test().test();
}
public void test(){
WordList wordList = new WordList();
wordList.add("One");
wordList.add("Two");
wordList.add("Three");
wordList.add("Four");
wordList.add("Two");
wordList.add("Five");
wordList.add("Six");
wordList.add("Six");
wordList.add("Two");
wordList.add("Seven");
wordList.add("Seven");
wordList.add("Two");
wordList.add("Two");
wordList.add("Seven");
System.out.println("There are "
+ String.valueOf(wordList.getOccurances("Two"))
+ " occurances of Two in this list.");
System.out.println("There are "
+ String.valueOf(wordList.getOccurances("Seven"))
+ " occurances of Seven in this list.");
System.out.println("There are "
+ String.valueOf(wordList.getOccurances("One"))
+ " occurances of One in this list.");
System.out.println("There are "
+ String.valueOf(wordList.getOccurances("Ten"))
+ " occurances of Ten in this list.");
}
}