Skip to content
Advertisement

How to find the longest string object in an arrayList

Here is is my problem, I have to explain a lot, because it’s a quite complicated.

I have created an arrayList<Word>, that contains strings as objects. In my case, I have three classes, all working together, that is supposed to represent a dictionary.

The first class is called “Word”, it has a constructor, and has simple methodes like .length, adds 1 to the counter, and keeps track of the words that are repeated.

The second class is called “Wordlist”, and uses more advanced methodes like reading a file, a summary of 30,000 words. Some methodes is for instance, to add words to the arraylist, as objects. Methods like search if they can find a perticular word. Now, these tasks contains parametres, with variables that I can use.

But I came upon a task in which I had to find the longest word(string) in the arrayList, without any parameters. The method is called: public Word findLongest().

In the thrid class, I have the test case, where I use the methodes. The most central part here is to read the file, and add it to the arrayList object. In what way can I use the method to find the longest word(string) in the arrayList without any parameters?

It is very confusing with arrayList as objects.

I am aware of the for (each : array) use in this sense, but have no idea how use it properly.

Advertisement

Answer

If your Word class provides a length() method which simply returns the length of the word represented by that object, then you can run through your ArrayList<Word> and find the longest like this:

private Word getLongestWordFromList(List<Word> listOfWords) {
    Word longestWord = null;
    for (Word word : listOfWords) {
        if (longestWord == null || word.length() > longestWord.length()) {
            longestWord = word;
        }
    }
    return longestWord;
}

The for (Word word : listOfWords) pattern simply says: iterate through the List called “listOfWords” and store the current Word object in a variable called “word”. Then you just check the length of each word to see whether it is longer than the longest already found. (If the longestWord variable is null then it means you haven’t processed any words so far, so whatever is the first Word found will go into that variable, ready to be compared with the next.)

Note: if there is more than one word with the longest length then this method will simply return the first word which is found with that length. If you need to return a list of all words having the longest length then you’ll need to modify this pattern to generate a List<Word> which contains all words of the longest length.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement