Created
November 23, 2015 11:52
-
-
Save rishi93/e19f0f730afb57b59564 to your computer and use it in GitHub Desktop.
Comparing Objects for sort, Comparable Interface.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
class A implements Comparable<A> | |
{ | |
private int data; | |
public A(int data) | |
{ | |
this.data = data; | |
} | |
@Override | |
public int compareTo(A ob) | |
{ | |
return ((Integer)this.data).compareTo(ob.data); | |
} | |
public int getData() | |
{ | |
return(this.data); | |
} | |
} | |
public class test2 | |
{ | |
public static void main(String[] args) | |
{ | |
A ob1 = new A(5); | |
A ob2 = new A(2); | |
A ob3 = new A(1); | |
List<A> newlist = new ArrayList<A>(); | |
newlist.add(ob1); | |
newlist.add(ob2); | |
newlist.add(ob3); | |
System.out.println("Before Sorting"); | |
for(A elem: newlist) | |
{ | |
System.out.print(elem.getData() + " "); | |
} | |
Collections.sort(newlist); | |
System.out.println("After Sorting"); | |
for(A elem: newlist) | |
{ | |
System.out.print(elem.getData() + " "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment