-1

I have an objects class that holds the properties title, director, genre, rating. I have created an arraylist and have filled it with instances of this base class

ArrayList<Movie> movieCatalog

I am wanting to sort this ArrayList in alphabetical order by the title property and change their positions within the ArrayList. From my research I understand I need to use a Comparator class but I am confused about how to do this.

0

2 Answers 2

0

You can create a custom comparator and than call the Collections.sort(movieCatalog,comparator); method.

E.g.

public static final Comparator<movieCatalog> movieComparator = new Comparator<movieCatalog>() {
        public int compare(movieCatalog a1, movieCatalog a2) {
            return a1.name.compareTo(a2.name);
        }
    };


Collections.sort(movieCatakig,movieComparator);
Sign up to request clarification or add additional context in comments.

4 Comments

But how would I change the positions of the objects within the ArrayList
When you call Collection.sort, and put the movieCatalog, and movieComparator, the arraylist is sorted for you. See: docs.oracle.com/javase/tutorial/collections/interfaces/…
I understand now. Thank you for your help unlike some other on this forum
Adding a custom comparator for such a simple case sounds like overkill. Implementing a compareto() method (like in the other answer below) sounds more sensible in this particular case
0

Your Movie class needs to implement Comparable<Movie>. Then you need to implement the compareTo method, which in this case can just call the String class compareTo method.

int compareTo(Movie other) {
    return this.title.compareTo(other.title);
}

After that, if movies is an ArrayList of movies, you can simply do

Collections.sort(movies);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.