1

I have an array list of 10 items. I want to sort this items by their parameters but I'm not exactly sure how.

The signature for my items in the array list is:

Creature(String n, Terrain startTerrain, boolean flying, boolean magic, boolean charge, boolean ranged, int combat)

So essentially I want to have my array list sorted so it's creatures where magic is true, they are first, then creatures where ranged is first, they appear next in the list, and then everything else.

I have only worked with bubble sort, and I'm not sure how to implement this. Any hints?

2
  • 3
    Collections.sort with a custom comparator. Commented Feb 12, 2014 at 22:19
  • You might also implement Comparable. Commented Feb 12, 2014 at 22:35

1 Answer 1

2

The easiest way would be to create your own class that implements Comparator<Creature>, say, CreatureComparator. Its compare method will define the order of your Creatures that you want.

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Then you can call Collections.sort(yourArrayList, new CreatureComparator());.

To sort by multiple attributes at once, test the first sort criterion first. I.e. if the left hand side's magic is true, but the right hand side's magic is false, then return -1, so that all magical creatures are before all non-magical creatures. If that's backwards, return 1. Only if the magic fields are the same do you start comparing the secondary and tertiary (and any other) sort criteria. So if the magic fields are the same, test ranged next, etc. Only if all of your sort criteria are the same would you return 0 (equivalent).

Sign up to request clarification or add additional context in comments.

2 Comments

I can see how to compare two things, but how can I sort by 3 things?
Please see my updated answer; I've explained how you could sort by multiple criteria at the same time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.