How to sort a vector elements that contains the user define
class object? (Note: If Suppose consider, A Student class
contain two data members. They are String studentName and
int rollNo. I am creating Four objects for this class, each
object contains students details like name and roll no. Now
i am storing that objects in vector and if i retiving the
elements from the vector means then it should be display in
sorting order)

Answer Posted / naren reddy

For sorting Any user defined class,We need to implement the
userdefined class with comparable or comparator
interfcae.Then only your collections.sort(ArrayList al)
will work,Otherwise it won't work.


Ex: class Employee implements Comparable{

private int age;

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

public int getAge(){
return this.age;
}public int compareTo(Object otherEmployee){

/*
If passed object is of type other than Employee,
throw ClassCastException.
*/

if(!(otherEmployee instanceof Employee)){
throw new ClassCastException("Invalid object");
}

int age = ((Employee) otherEmployee).getAge();

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

}

}

Is This Answer Correct ?    2 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is difference between stringbuffer and string?

722


What happens if we override private method?

736


Tell some latest versions in JAVA related areas?

761


Which of the following is not an isolation level in the JDBC

1885


What does the “static” keyword mean?

817


What is a treemap in java?

753


Explain the difference between association, aggregation and inheritance relationships.

811


What is the file extension for java?

838


How many types of design patterns are there?

788


Can we catch more than one exception in single catch block?

841


What is string [] java?

736


What is difference between float and double?

697


What is the use of generics? When was it added to the Java development Kit?

763


Describe the syntax of multiple inheritance? When do we use such an inheritance?

822


Does java allow default arguments?

778