Home | Login | Blog | Forum | Download | RSS Feed | Ajax | Hello-World | J2EE | BPM | EJB | FileNet | Hibernate | ORM | IBM | ILOG | Interview | FAQs |

Java | Apache | JVM | Others | BRMS | Oracle | Pega | SOA | Sun-Certification | Web-Service | websphere | XML |
 

JAVA DEVELOPER SITE - COMPLETE JAVA TUTORIALS

Java Comparable and Comparator Interface


Share
 
 

Useful Java Links


       


Java Comparable and Comparator Interface

 

            The Collections and Arrays can sorted using the method  in the API. Java.util.Colections,sort() and Arrays.sort() method is used to sort the Collections and Arrays. Remember that argument passed to Collections.sort() method must implement the Comparable interface otherwise we will get a compilation error.

 

The Comparable Interface:

·         This interface is used by Collections.sort() and Arrays.sort() method to sort the list and array of objects.

·         To implement this interface , a class must implement a single method compareTo().

·         Let us see  the  invocation of compareTo() method:

                        int  x= thisObject.compareTo(anotherObject);

            Here compareTo() to method returns an int     with the following meaning

                                               

·         negative           ----- if thisObject  <   anotherObject

·         zero                 ----- if thisObject == anotherObject

·         positive            ----- if thisObject  >    anotherObject

·         Before generics the compareTo() method takes an Object rather than a specific type. Here we have to cast object to specific type. For example see  below code

 

        class DVDInfo implements Comparable {

                                    //some code

                        public int compareTo(Object o){

                       

                                    DVDInfo d= (DVDInfo) o ;

                                    return title.compareTo(d.getTitle));

                        }

            }

 

The Comparator Interface

·         The Comparator interface gives you  the capability to sort collection in different ways.

·         This interface is used sort instance of any class even if classes you can't modify.

·         To implement this interface , a class must implement a single method compare().

·         Comparator.compare() method returns an int whose meaning is same as Comparable.compareTo() method's return value.

 

Comparing Comparable to Comparator :

 

Java.lana.Comparable

Java.util.Comparator

Int objeone.compareTo(objTwo);

Int compare(objOne, objTwo)

Returns

            negative    if objOne<objTwo

            zero           if objOne == objTwo

            positive     if objOne  > objTwo

 

Same as Comparable

We must modify the class whose instances we want to sort.

We build a class separate from the class whose instances we want to sort

Only one sort sequence can be created

Many sort sequence can be created

Implemented frequently in the API by:

String, Wrapper classes, Date, Calender....

Meant to be implemented to sort instances of third party classes.

 

 

 

Let us see the example for both  Comparator and Comparable.

 

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.Iterator;

 

 

public class Student implements Comparable<Student> {

            private String name;

            private int score;

           

            public Student(String name, int score) {

                        this.name = name;

                        this.score = score;

            }

 

            public int compareTo(Student obj){

                        Integer i=new Integer(score);

                        return i.compareTo(obj.score);

            }

                       

 

            public static void main(String args[]) {

                 ArrayList<Student> list = new ArrayList<Student>();

                   

                 list.add(new Student("Ann", 87));

                 list.add(new Student("Bob", 83));

                 list.add(new Student("Cat", 99));

                 list.add(new Student("Dan", 25));

                 list.add(new Student("Eve", 76));

                

                 Iterator<Student> iter = list.iterator();

                 while (iter.hasNext()) {

                    Student s = iter.next();

                    System.out.println(s.name + "  " + s.score);

                 }

                 System.out.println("Sorted List");

                 Collections.sort(list);

                 Iterator<Student> iter1 = list.iterator();

                 while (iter1.hasNext()) {

                    Student s = iter1.next();

                    System.out.println(s.name + "  " + s.score);

                 }

                

                 StudentName st1= new StudentName();

                 Collections.sort(list,st1);

                 Iterator<Student> iter2 = list.iterator();

                 while (iter2.hasNext()) {

                    Student s = iter2.next();

                    System.out.println(s.name + "  " + s.score);

                 }

                

               

                }

            static class StudentName implements Comparator<Student>{

                        public int compare(Student o1, Student o2) {

                                    return o1.name.compareTo(o2.name);

                        }

            }

}

 

 




Download Latest Java/J2EE eBooks, SCJP Dumps, SCWCD Dumps, Pega Tutorial, IBM WebSphere BPM tutorials and many more


If you need any urgent assistance on Java-Comparable-and-Comparator-Interface, kindly email your requirement to us at : info@javagenious.com or Contact-an-Expert. Our experts will try their best to solve your problem.

You can also subscribe to our newsletters on Java-Comparable-and-Comparator-Interface, to receive updates on Java-Comparable-and-Comparator-Interface,via email.Enter you email below:

Enter your email address:

Delivered by FeedBurner



Keyword Tags: Java-Comparable-and-Comparator-Interface tutorial,Java-Comparable-and-Comparator-Interface in java,Concepts of Java-Comparable-and-Comparator-Interface,Java,J2EE,Interview Questions,Java-Comparable-and-Comparator-Interface Examples


Comments:


Post Your Comment:

*

Yes, I would like to recieve email notifications on my reply.

Popular Posts:

 
Popular Downloads

SCJP 1.6 Dumps
JSP Interview Questions
Struts Interview Questions
Hibernate Interview Questions
SCWCD Dumps
SCBCD Dumps

Java/J2EE Tutorial
JMS Tutorials
seam richfaces tutorial
richfaces live demo
jquery example demo
JQuery Tutorial and Source Code
JSF Tutorial
XSL Tutorial
J2EE JMS
CORBA Applications
Java CERTIFICATION
SCJP 1.5
SCJP 1.6
SCWCD 1.5
SCBCD
Mis
Ajax autosuggest autocomplete from database
Struts forms and validation with webflow
Java Apache POI Examples
JDBC Tutorial
Oracle 9i & 10g
MYSQL Tutorial
php Tutorial
JQuery Examples
Upload Java File
JAXB Examples
PL-SQL Tutorial
Dojo AJAX
EJB Examples
Java IDE
Eclipse
NetBeans
IBM Rational Weblogic Workshop
Downloads
SCJP 1.6 Dumps
SCJP 1.5 DUMP
SCJP Material
SCWCD
Java Security
SCBCD Dumps
External Links
SUN Java
JOracle
IBM
PHP Certification
Technical Interview Questions
Amazon Interview Questions
Google Interview Questions
Microsoft Interview Questions
IBM Interview Questions
Yahoo Interview Questions
All Tutorials
php mysql tutorial
SCJP 1.5/1.6
SCWCD 1.5/1.6
Polymorphism
Thread Tutorial
Generics & Exceptions
Spring Struts Hibernate
Java Collections
MAP
SET
LIST
VECTOR
Advanced Java
Stateless Session Bean
Introduction to EJB
Stateful Session Bean
Java Design Patterns
HOME | FORUM | ABOUT | BLOGS | CONTACT-US