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
What are nested classes in java?
Which package has light weight components in java programming?
What are the advantages of exception handling?
What do you mean by formatting?
Can an interface be defined inside a class?
What is the basic concepts of OOPS?
You can create a string object as string str = “abc”; why cant a button object be created as button bt = “abc”;? Explain
What are the differences between checked exception and unchecked exception?
What is null object in java?
Why does java not allow multiple public classes in a java file ?
Why we do exception handling in java and how many types of exceptions are there?
How to display arraylist values in java?
How many bits is a string?
What is boolean data type in java?
What does @override mean?