Tomas1337
Tomas1337

Reputation: 1

Using compareTo in ArrayLists

I need some help using compareTo in ArrayLists. As a guide I was given this paragraph:

addOrder(ArrayList words, String newWord) – this method adds newWord in the proper alphabetical order.

Hint you can use: x.compareTo(y)

If x.compareTo(y) is < 0, x comes before y)

addOrder should then return this updated ArrayList of Strings.

But even though I researched alot still struggling to understand how to apply it to ArrayLists. This is my code that I want to use the compareTo method:

import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;

class StringList {
    public static void main(String [] args)
    {
        ArrayList< String> list = new ArrayList< String>();
        list.add("Goldsmiths");
        list.add("College");
        list.add("London");
        list.add("Manchester");
        list.add("London");
        list.add("York");
        System.out.println("These are your words:");
        System.out.println(list);
        System.out.println("This is the size of the array:");
        System.out.println(lengthArray(list));
        System.out.println("The length of all strings is:");
        System.out.println(totalLengthArray(list));
    }

    public static int lengthArray(List<String> list)
    {
        return list.size();
    }

    public static int totalLengthArray(List<String> list)
    {
        int count = 0;
        for (String s: list)
        {
            count += s.length();
        }
        return count;
    }
}

I want to compare and sort out the list items that I have added which you can see in my code.

Upvotes: 0

Views: 4463

Answers (2)

Sergey Shustikov
Sergey Shustikov

Reputation: 15821

Use a Collections.sort(List<T> list, Comparator<T> c);

Collections.sort(yourList,new Comparator<String>() {
    @Override
    public int compare(String lhs, String rhs) {
        return lhs.compareTo(rhs);   //or whatever your sorting algorithm
    }
});

Upvotes: 3

Karura91
Karura91

Reputation: 623

compareTo is a method of String class. So, in order to use it, you have to write something like this:

list.get(i).compareTo(newWord)

where i is the index of an element of your list and newWord is the newWord.

Here is an useful link

You could simple add an element and then use Collections.sort(list) but since I think this is a school assignment probably you can't, so you have to manage the insert manually using compareTo method as I showed you.

Upvotes: 1

Related Questions