Sarah
Sarah

Reputation: 2903

How to sort an array list by it's parameters?

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?

Upvotes: 1

Views: 77

Answers (1)

rgettman
rgettman

Reputation: 178263

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).

Upvotes: 2

Related Questions