Results 1 to 4 of 4
Thread: Sorting ArrayList special issue
- 06-11-2012, 06:08 PM #1
Member
- Join Date
- Sep 2011
- Posts
- 17
- Rep Power
- 0
Sorting ArrayList special issue
I have a class Location that takes 3 parameters x y and z. I have an arraylist of Location and I am trying to sort these locations by ascending order.
Now I read about arraylist.sort() but how can I sort the locations according to a certain parameter, say the y parameter???
thanks
- 06-11-2012, 06:15 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
Re: Sorting ArrayList special issue
Object Ordering (The Java™ Tutorials > Collections > Interfaces)
Collections (Java Platform SE 6), java.util.Comparator)
Comparator (Java Platform SE 6)
Java Code:Collections.sort(yourArrayList, new Comparator<Location>() { @Override public int compare(Location o1, Location o2) { return ..... //your logic here... } });
- 06-11-2012, 11:09 PM #3
Member
- Join Date
- Sep 2011
- Posts
- 17
- Rep Power
- 0
Re: Sorting ArrayList special issue
well that's what I've been trying and I can't figure it out (sorry im a beginner)
I tried
and I get "Cannot invoke compareTo(int) on the primitive type int"Java Code:final Comparator<AddressLoc> highestLevel = new Comparator<AddressLoc>() { @Override public int compare(AddressLoc o1, AddressLoc o2) { return o1.getZ().compareTo(o2.getZ()); } };
- 06-12-2012, 06:59 AM #4
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
Re: Sorting ArrayList special issue
Yes because you can`t invoke methods on primitives!
You could write return o1.getZ() - o2.getZ();
but that could lead to a wrong result.
but you could use some if statements (or ternary operator)?
if(o1.getZ() == o2.getZ()) return .... else if(o1.getZ() > o2.getZ()) return .... else return ....
Similar Threads
-
Sorting Array Issue
By larson1118 in forum New To JavaReplies: 2Last Post: 04-21-2011, 05:31 PM -
sorting arraylist based on another arraylist
By busdude in forum New To JavaReplies: 4Last Post: 02-07-2011, 11:48 AM -
XHTML to FO Transformation Issue for Special Characters
By simsu123 in forum Advanced JavaReplies: 1Last Post: 06-30-2010, 12:04 AM -
Sorting an ArrayList
By flesh-bound-book in forum New To JavaReplies: 3Last Post: 02-13-2010, 12:20 PM -
is the any special issue regarding the insertion in msacess 2007
By javastuden in forum JDBCReplies: 3Last Post: 01-25-2010, 07:18 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks