Results 1 to 3 of 3
Thread: object list sorting
- 10-08-2010, 05:09 PM #1
Member
- Join Date
- May 2010
- Posts
- 63
- Rep Power
- 0
object list sorting
Hey!
If i want to sort a object list by a random variable do I really have to make implementation class for every variable?
example:
list of car objects
Java Code:class car { int id; String brand; int year; //Setters & getters } class carID implements Comparable{ public int compare(Object car, Object anotherCar) { int id = car.getId(); int id2 = anotherCar.getId(); return id.compareTo(id2); } } class carBrand implements Comparable{ public int compare(Object car, Object anotherCar) { String brand = car.getBrand(); String brand2 = anotherCar.getBrand(); return brand.compareTo(brand2); } } ..... Or is there another way?
- 10-08-2010, 05:42 PM #2
Class names should start with upper-case letters. But you could also do something like this:
Then just set the condition of the comparing class whenever you want to use it. I don't really see the "problem" you're trying to work around, though.Java Code:class carID implements Comparable{ public int compare(Object car, Object anotherCar) { if(condition){ int id = car.getId(); int id2 = anotherCar.getId(); return id.compareTo(id2); } else{ String brand = car.getBrand(); String brand2 = anotherCar.getBrand(); return brand.compareTo(brand2); } }
- 10-08-2010, 05:45 PM #3
Similar Threads
-
Need help with sorting a linked list
By SteroidalPsycho in forum New To JavaReplies: 0Last Post: 05-04-2010, 01:15 AM -
list sorting problem.
By bit_bit in forum Advanced JavaReplies: 2Last Post: 02-26-2010, 04:17 AM -
List Sorting method.
By bit_bit in forum New To JavaReplies: 1Last Post: 02-24-2010, 11:44 AM -
Sorting a linked list
By Hayzam in forum New To JavaReplies: 4Last Post: 01-18-2009, 12:07 AM -
Converting array to list and sorting it
By Java Tip in forum java.langReplies: 0Last Post: 04-16-2008, 10:36 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks