-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.

batsta13
  • 549
  • 2
  • 12
  • 26

2 Answers2

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);
Menelaos
  • 23,508
  • 18
  • 90
  • 155
  • But how would I change the positions of the objects within the ArrayList – batsta13 May 26 '13 at 22:13
  • When you call `Collection.sort`, and put the movieCatalog, and movieComparator, the arraylist is sorted for you. See: http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html – Menelaos May 26 '13 at 22:16
  • I understand now. Thank you for your help unlike some other on this forum – batsta13 May 26 '13 at 22:18
  • 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 – Filippos Karapetis May 27 '13 at 21:15
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);
Imre Kerr
  • 2,388
  • 14
  • 34