Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

12.6. Comparator Interface

Several methods in the class Collections assume that the objects in the collection are comparable. If there is no natural ordering, a helper class can implement the interface Comparator to specify how the objects are to be ordered.

public class Crayon {
private String color;
public void setColor(String s)
{color = s;}
public String getColor()
{return color;}
public String toString()
{return color;}
}

import java.util.Comparator;
public class CrayonSort implements Comparator {
public int compare (Crayon one, Crayon two) {
return one.getColor().compareTo(two.getColor());
}
}

import java.util.ArrayList;
import java.util.Collections;
public class ComparatorTest {
public static void main(String[] args) {
Crayon crayon1 = new Crayon();
Crayon crayon2 = new Crayon();
Crayon crayon3 = new Crayon();
Crayon crayon4 = new Crayon();
crayon1.setColor("green");
crayon2.setColor("red");
crayon3.setColor("blue");
crayon4.setColor("purple");
CrayonSort cSort = new CrayonSort();
ArrayList cList = new
ArrayList();
cList.add(crayon1);
cList.add(crayon2);
cList.add(crayon3);
cList.add(crayon4);
Collections.sort(cList, cSort);
System.out.println("\nSorted:" + cList );
}
}

$ Sorted: [blue, green, purple, red]

					  


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint