Results 1 to 4 of 4
  1. #1
    garnaout is offline Member
    Join Date
    Sep 2011
    Posts
    17
    Rep Power
    0

    Default 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

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default 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...
    			}
    		});

  3. #3
    garnaout is offline Member
    Join Date
    Sep 2011
    Posts
    17
    Rep Power
    0

    Default 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

    Java Code:
     final Comparator<AddressLoc> highestLevel = 
                    new Comparator<AddressLoc>() {
    
                @Override
                public int compare(AddressLoc o1, AddressLoc o2) {
                    
                    return o1.getZ().compareTo(o2.getZ());
                }
    
            };
    and I get "Cannot invoke compareTo(int) on the primitive type int"

  4. #4
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default 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

  1. Sorting Array Issue
    By larson1118 in forum New To Java
    Replies: 2
    Last Post: 04-21-2011, 05:31 PM
  2. sorting arraylist based on another arraylist
    By busdude in forum New To Java
    Replies: 4
    Last Post: 02-07-2011, 11:48 AM
  3. XHTML to FO Transformation Issue for Special Characters
    By simsu123 in forum Advanced Java
    Replies: 1
    Last Post: 06-30-2010, 12:04 AM
  4. Sorting an ArrayList
    By flesh-bound-book in forum New To Java
    Replies: 3
    Last Post: 02-13-2010, 12:20 PM
  5. Replies: 3
    Last Post: 01-25-2010, 07:18 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •