Java Comparable Example

Java Comparable Example

I want to know the use of Comparable Interface. Please provide me one example

View Answers

June 22, 2012 at 12:24 PM

Comparable interface is used to define the natural sort order of a class.List of objects that implement this interface can be sorted automatically by sort method of the list interface. This interface has compareTo() method that is used by the sort() method of the list.

Here is an example that compares two ages using Comparable Interface.

import java.util.*;

class Person implements Comparable{
    int age;

    public void setAge(int age){    
        this.age=age;
    }
    public int getAge(){    
        return this.age;    
    }

    public int compareTo(Object ob){
        if(!(ob instanceof Person)){
            throw new ClassCastException("Invalid object");
        }

        int age = ((Person) ob).getAge();

        if(this.getAge() > age)    
            return 1;
        else if ( this.getAge() < age )
            return -1;
        else
            return 0;

    }
 }
 public class ComparableExample{

    public static void main(String args[]){

        Person one = new Person();        
        one.setAge(35);

        Person two = new Person();        
        one.setAge(30);

        if(one.compareTo(two) > 0) {        
            System.out.println("Person one is elder than Person two!");

        } else if(one.compareTo(two) < 0) {        
            System.out.println("Person one is younger than Person two!");        

        } else if(one.compareTo(two) == 0) {        
            System.out.println("Both Persons are same!");        
        }
     }
 }

August 31, 2012 at 12:58 PM

public class Employee implements Comparable<Employee> {

    int empId;
    String eName;

    public Employee(int empId, String eName) {
        super();
        this.empId = empId;
        this.eName = eName;
    }
    @Override
    public String toString() {

        return "ID:"+empId+"NAME:"+eName;   
    }
    @Override


    public int compareTo(Employee e) {

        return  eName.compareTo(e.eName);
    }

}

import java.util.Iterator;
import java.util.TreeSet;

public class EmpMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        TreeSet<Employee> ts =new TreeSet<Employee>();
        ts.add(new Employee(123,"vijay"));
        ts.add(new Employee(98,"kumar"));
        ts.add(new Employee(100,"abhi"));
        ts.add(new Employee(50,"dhruv"));
        ts.add(new Employee(150,"sasi"));

        for (Iterator iterator = ts.iterator(); iterator.hasNext();) {
            Employee employee = (Employee) iterator.next();
            System.out.println(employee);
        }

    }

}

August 31, 2012 at 12:59 PM

output:

ID:100NAME:abhi ID:50NAME:dhruv ID:98NAME:kumar ID:150NAME:sasi ID:123NAME:vijay

Ads









Related Tutorials/Questions & Answers:
Java Comparable Example
Java Comparable Example  I want to know the use of Comparable Interface. Please provide me one example   Comparable interface is used.... Here is an example that compares two ages using Comparable Interface. import
ModuleNotFoundError: No module named 'Comparable'
ModuleNotFoundError: No module named 'Comparable'  Hi, My Python... 'Comparable' How to remove the ModuleNotFoundError: No module named 'Comparable' error? Thanks   Hi, In your python environment you
Advertisements
ModuleNotFoundError: No module named 'Comparable'
ModuleNotFoundError: No module named 'Comparable'  Hi, My Python... 'Comparable' How to remove the ModuleNotFoundError: No module named 'Comparable' error? Thanks   Hi, In your python environment you
ModuleNotFoundError: No module named 'manhattan-comparable'
ModuleNotFoundError: No module named 'manhattan-comparable'  Hi...: No module named 'manhattan-comparable' How to remove the ModuleNotFoundError: No module named 'manhattan-comparable' error? Thanks   Hi
ModuleNotFoundError: No module named 'type-comparable'
ModuleNotFoundError: No module named 'type-comparable'  Hi, My... named 'type-comparable' How to remove the ModuleNotFoundError: No module named 'type-comparable' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'type-comparable'
ModuleNotFoundError: No module named 'type-comparable'  Hi, My... named 'type-comparable' How to remove the ModuleNotFoundError: No module named 'type-comparable' error? Thanks   Hi, In your python
java persistence example
java persistence example  java persistence example
Java Client Application example
Java Client Application example  Java Client Application example
Example of HashSet class in java
Example of HashSet class in java. In this part of tutorial, we... unique. You can not store duplicate value. Java hashset example. How.... Example of Hashset iterator method in java. Example of Hashset size() method
What is array in java with example?
What is array in java with example?  Hi, I am beginner in Java and want to learn Java Array concepts. Which is the best tutorials for learn Java Array with example codes? What is array in java with example? Thanks
Java FTP Client Example
Java FTP Client Example  How to write Java FTP Client Example code? Thanks   Hi, Here is the example code of simple FTP client in Java which downloads image from server FTP Download file example. Thanks
Example of HashMap class in java
Example of HashMap class in java. The HashMap is a class in java collection framwork. It stores values in the form of key/value pair. It is not synchronized
FTP Java example
FTP Java example  Where is the FTP Java example on your website? I am... examples of FTP at: FTP Programming in Java tutorials with example code. Thaks... functionality in my Java based application. My application is swing based and I have
Need an Example of calendar event in java
Need an Example of calendar event in java  can somebody give me an example of calendar event of java
Java FTP Example
Java FTP Example  Is there any java ftp example and tutorials... and tutorials that teaches you how to user FTP in your Java project. Most commonly used FTP api in java is Apache FTP. Browse all the FTP tutorials at Java FTP
java string comparison example
java string comparison example  how to use equals method in String... strings are not same. Description:-Here is an example of comparing two strings using equals() method. In the above example, we have declared two string
Java nested class example
Java nested class example  Give me any example of Nested Class.   Nested Class: Class defined within another class is called nested class... class. Example: public class NestedClass{ private String outer = "Outer
throws example program java
throws example program java  how to use throws exception in java?   The throws keyword is used to indicate that the method raises..." java.lang.ArithmeticException: / by zero Description:- Here is an example of throws clause. We
what is the example of wifi in java
what is the example of wifi in java  i want wi fi programs codings
Java hashset example.
Java hashset example.     HashSet is a collection. You can not store duplicate value in HashSet. In this java hashset exmple, you will see how to create HashSet in java application and how to store value in Hashset
example
example  example on Struts framework
example
example  example on Struts framework
Java collection Stack example
:- -1 Description:- The above example demonstrates you the Stack class in java...Java collection Stack example  How to use Stack class in java.... Here is an example of Stack class. import java.util.Stack; public class
Inheritance java Example
Inheritance java Example  How can we use inheritance in java program... for bread Description:- The above example demonstrates you the concept... properties of the superclass. In the given example, the class Animal is a superclass
Java Comparator Example
Java Comparator Example  Can you provide me an example of Comparator Interface?   A comparator object is capable of comparing two different... is an example that compares the object of class Person by age. import java.util.
Java HashMap example.
Java HashMap example. The HashMap is a class in java. It stores values in name values pair. You can store null value of key and values.   Here... of map. Code:  HashMapExample .java package net.roseindia.java
Java Map Example
Java Map Example  How we can use Map in java collection?   The Map interface maps unique keys to value means it associate value to unique... Description:- The above example demonstrates you the Map interface. Since Map
Java File Management Example
of file. Read the example Read file in Java for more information on reading...Java File Management Example  Hi, Is there any ready made API in Java for creating and updating data into text file? How a programmer can write code
java binary file io example
java binary file io example  java binary file io example
Core java linked list example
Core java linked list example  What is the real time example for linked list
Static Method in java with realtime Example
Static Method in java with realtime Example  could you please make me clear with Static Method in java with real-time Example

Ads