Java Comparable interface is used to order the objects of user-defined
class.
This interface is found in java.lang package and contains only one method named compareTo(Object).
It provide single sorting sequence only i.e. you can sort the elements on based on single data member only.
For example it may be rollno, name, age or anything else.
Example:
package practice;
public class programming implements Comparable<programming>{
int age;
String name;
int rollno;
programming(int rollo,String name,int age) {
this.rollno=rollo;
this.age=age;
this.name=name;
}
@Override
public int compareTo(programming o) {
if(age==o.age){
return 0;
}
else if (age>o.age)
return 1;
else
return -1;
}
}
Second Class
package practice;
import java.util.ArrayList;
import java.util.Collections;
public class testComparable {
public static void main(String[] args) {
ArrayList<programming> ls=new ArrayList<programming>();
ls.add(new programming(11,"A",7));
ls.add(new programming(18,"A",17));
ls.add(new programming(17,"A",11));
ls.add(new programming(21,"A",9));
Collections.sort(ls);
for(programming ok:ls){
System.out.println(ok.age);
}
}
}
Output
7
9
11
17
This interface is found in java.lang package and contains only one method named compareTo(Object).
It provide single sorting sequence only i.e. you can sort the elements on based on single data member only.
For example it may be rollno, name, age or anything else.
Example:
package practice;
public class programming implements Comparable<programming>{
int age;
String name;
int rollno;
programming(int rollo,String name,int age) {
this.rollno=rollo;
this.age=age;
this.name=name;
}
@Override
public int compareTo(programming o) {
if(age==o.age){
return 0;
}
else if (age>o.age)
return 1;
else
return -1;
}
}
Second Class
package practice;
import java.util.ArrayList;
import java.util.Collections;
public class testComparable {
public static void main(String[] args) {
ArrayList<programming> ls=new ArrayList<programming>();
ls.add(new programming(11,"A",7));
ls.add(new programming(18,"A",17));
ls.add(new programming(17,"A",11));
ls.add(new programming(21,"A",9));
Collections.sort(ls);
for(programming ok:ls){
System.out.println(ok.age);
}
}
}
Output
7
9
11
17
No comments:
Post a Comment