Sorting with Comparator : Comparable « Utility Classes « SCJP

Home
SCJP
1.Java Source And Data Type
2.Operators
3.Modifiers
4.Type Casting
5.Statements
6.Object Oriented
7.Thread
8.Utility Classes
9.File
SCJP » Utility Classes » Comparable 
8.19.1.Sorting with Comparator
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class GenreSort implements Comparator<Movie> {
  public int compare(Movie one, Movie two) {
    return one.getGenre().compareTo(two.getGenre());
  }
}

class Movie implements Comparable<Movie> {
  String title;

  String genre;

  String leadActor;

  Movie(String t, String g, String a) {
    title = t;
    genre = g;
    leadActor = a;
  }

  public String toString() {
    return title + " " + genre + " " + leadActor + "\n";
  }

  public int compareTo(Movie d) {
    return title.compareTo(d.getTitle());
  }

  public String getTitle() {
    return title;
  }

  public String getGenre() {
    return genre;
  }

  public void setGenre(String genre) {
    this.genre = genre;
  }
}

public class MainClass {

  public static void main(String[] args) {
    ArrayList<Movie> dvdlist = new ArrayList<Movie>();
    System.out.println(dvdlist)// output as read from file
    Collections.sort(dvdlist);
    System.out.println(dvdlist)// output sorted by title

    GenreSort gs = new GenreSort();
    Collections.sort(dvdlist, gs);
    System.out.println(dvdlist)// output sorted by genre
  }
}
[]
[]
[]
8.19.Comparable
8.19.1.Sorting with Comparator
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.