[Solved] Sort ArrayList

Discussion in 'Plugin Development' started by Moon_werewolf, Mar 12, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    Moon_werewolf

    I would like to know if the are a way to sort things in a ArrayList. The array saves blocks and i need to have them in order. Like 50, 9, 11, 8, 10 and rest. so when my nanobot plugin removes something it remove the torches first. then lava and water. but now everything is just in a big mess in that array.

    i have so far just loop through the array 3 times to remove the things i want... but that solution is so slow. So I'm looking for a better one.
     
  2. Offline

    Father Of Time

    It's a built in ArrayList feature (and most collections ):
    http://docs.oracle.com/javase/1.4.2...ml#sort(java.util.List, java.util.Comparator)


    So you can either sort by built in coparators or create your own:

    http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Comparator.html

    You can create a custom comparator to compare specific features of a class, say in your instance the material type of a block class.

    Here is a random comparator class I found on Google to give you an idea:


    Code:
    class AgeComparator implements Comparator
    {
        public int compare(Object emp1, Object emp2)
        {
            int emp1Age = ((Employee)emp1).getAge();       
            int emp2Age = ((Employee)emp2).getAge();
            if(emp1Age > emp2Age)
                return 1;
     
            else if(emp1Age < emp2Age)
                return -1;
     
            else
            return 0;   
        }
    }
    And that should do the trick.

    I hope this helps, good luck with your project!
     
  3. Offline

    Moon_werewolf

    The problem with that is the ArrayList saves the class NanoMemmory (ArrayLis<NanoMemmory>) so i don't think a coparator could work. If i made a custom one i need to loop through the array everytime i add something to it... and the array is huge
     
  4. Offline

    nisovin

    If the NanoMemory object is actually sortable, then it's possible to create a Comparator for it. If you claim it's not possible, then that means that your object is not sortable. You could also make your NanoMemory class implement Comparable and implement the compareTo method.

    Edit: If you go the Comparable route, you should consider using a TreeSet rather than an ArrayList.
     
  5. Offline

    Moon_werewolf

    Thanks :) now i can very easily sort the array without looping it 3 times :D
     
Thread Status:
Not open for further replies.

Share This Page