Comparable Interface:
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. You can sort the elements on based on single data member only. For example it may be marks, name or anything else.
Code:
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. You can sort the elements on based on single data member only. For example it may be marks, name or anything else.
Code:
- import java.util.Set;
- public class Student implements Comparable<Student> {
- public int marks;
- public String name;
- public Student(int marks,String name){
- this.marks=marks;
- this.name=name;
- }
- public int compareTo(Student st1){
- if (marks==st1.marks){
- return 0;
- }
- else if (marks>st1.marks) {
- return 1;
- }
- else {
- return -1;
- }
- }
- }
- //Main class.....
- import java.awt.List;
- import java.util.ArrayList;
- import java.util.Collections;
- public class Collection_interface {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- ArrayList<Student>studentList=new ArrayList<Student>();
- studentList.add(new Student(50,"Shimul"));
- studentList.add(new Student(45,"Sujan"));
- studentList.add(new Student(70, "Shakil"));
- Collections.sort(studentList);
- for(Student st: studentList){
- System.out.println(st.name+" "+st.marks);
- }
- }
- }
0 Comments:
Post a Comment