Java Reference
In-Depth Information
Person hold = list[h];
int k = h - 1; //start comparing with previous item
while (k >= 0 && hold.name.compareToIgnoreCase(list[k].name) < 0) {
list[k + 1] = list[k];
--k;
}
list[k + 1] = hold;
} //end for
} //end insertionSort
We could sort, by name, the array
person
from Program P2.3 with the following call:
insertionSort(person, 0, person.length - 1);
In the
while
condition, we compare the
name
field of the person being processed (the one in position
h
) with
the
name
field of an array element.
2.14 Using a Class to Group Data: Word Frequency Count
In Section 1.8, we wrote a program (Program P1.7) to do a frequency count of the words in a passage. There, we used
a
String
array (
wordlist
) to hold the words and an
int
array (
frequency
) to hold the frequencies. The code was
written such that
frequency[i]
held the count for the word in
wordlist[i]
. We now show how to solve the same
problem in a slightly different way by using a class.
We can think of each word in the passage as an object with two attributes—the letters in the word and the
number of times it appears. We will define a class,
WordInfo
, from which we will create “word objects.”
class WordInfo {
String word;
int freq = 0;
WordInfo(String w, int f) {
word = w;
freq = f;
}
void incrFreq() {
freq++;
}
} //end class WordInfo
The class has two fields:
word
and
freq
. It has a constructor to initialize a
WordInfo
object to a given word and
frequency. It also has a method to add 1 to the frequency of a word. Suppose
wo
is a
WordInfo
object created with this
statement:
WordInfo wo = new WordInfo(aWord, 1); //String aWord
wo.word
refers to the word, and
wo.freq
is its frequency. And we can add 1 to its frequency with
wo.incrFreq()
.
Next, we will define a
WordInfo
array; each element will hold information about one word.
WordInfo[] wordTable = new WordInfo[MaxWords + 1];
Search WWH ::
Custom Search