Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

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

How the metacharacters are different from the ordinary characters?

982


These static constructors are correct ? class A { statc intA() { } static A(int x,int y) { } static A(int x) { } }

1040


What is hash in java?

913


Can an arraylist be empty?

1017


State the difference between creating string as new () and literal.

1038


If a variable is declared as private, where may the variable be accessed?

1012


What data type is true or false?

1000


Is it possible for a yielded thread to get chance for its execution again?

900


What is the difference between == and === javascript?

1104


What is the meaning of variable in research?

964


In how many ways we can create threads in java?

1147


Why map is used in java?

990


What is the use of protected in java?

984


Is 64bit faster than 32 bit?

1022


What is bitwise complement?

936