![]() |
about sort()-method
Here's the problem little simplified:
I have made two classes Person and CardIndex. I created Objects from both Person myP = new Person("FirstName", "LastName"); CardIndex cInd = new CardIndex(); CardIndex is basically a vector where I dump those Persons. Classes have some other stuff in them too, and Person is a super-class for two other Classes, so in CardIndex-vector can be at least three kind of classes or something like that. Problem: I have to sort the cInd by LastName using sort()-method. I'm lost :confused: //Collections.sort(cInd**!*"*#) brainMalfunction. Thanks for any help. |
You need a custom Comparator to tell Java how to sort. Comparator objects have a "compare" method that takes two Objects as arguments and returns an integer. If the integer is negative, the first object is less than the second; if the integer is positive, the first object is greater than the second; if the integer is 0, the objects are equal. The String.compareTo method can compare two strings in this way.
You can use an anonymous class to save cluttering up your code with a class that will only be used once. Maybe something like: :
Collections.sort(cInd, new Comparator() { |
Shouldn't that be :
:
Collections.sort(cInd, new Comparator() { |
Yes, you're right. Though, if you have Java 1.5:
:
Collections.sort(cInd, new Comparator<Person>() { |
Quote:
cInd {Person("FN", "LN"), Student("FN", "LN"), Worker("FN", "LN")} <- not meant to be anykind of syntax :) just to clarify things. Student and Worker are descended from Person. Thanks for these tips allready, I'll try to get forward in this but I really am miserable in this. |
Quote:
Before Java 1.5, you had to cast an element as the correct type when removing it from a container: :
Vector list = new Vector();:
Vector<String> list = new Vector<String>();:
Vector<Person> persons = new Vector<Person>();Quote:
|
OK thank you guys, finally got it working. Had some problems with the whole idea (what to do in which class etc). Post my solution here if it may help someone else.
:
In class Person: |
| All times are GMT -5. The time now is 11:27 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC