wai kwan Chiu wai kwan Chiu - 1 year ago 61
Java Question

Java ArrayList sort with multi object

There 4 type class:
Class A,Class B,Class C, Class D

Class attribute:
Class A:aID,name,sequence
Class B,bID,amount,sequence
Class C,cID,price,sequence
Class D,dID,date,sequence

The attributes of those class is different. However, they have the same attribute "Sequence".

For example, i created a ArrayList to store those object.

item 1(Class A) = Sequence(4)
item 2(Class D) = Sequence(2)
item 3(Class C) = Sequence(3)
item 4(Class B) = Sequence(1)
item 5(Class C) = Sequence(5)

How can i sort this list into this order?

item 1(Class B) = Sequence(1)
item 2(Class D) = Sequence(2)
item 3(Class C) = Sequence(3)
item 4(Class A) = Sequence(4)
item 5(Class C) = Sequence(5)

Answer Source

The can think in two ways to archieve what you want:

Your own method

It's not hard to create a method to do the sorting, but you would have to implement your own sorting algorithm.


Here you can find a fine example on the accepted answer, you could just use that with a little difference:

If all your classes extend the same class or implement the same interface, instead of MyObject you can use the parent class. (They SHOULD implement a common interface).

Else, you can just use Object and chain several "instanceof" and casts to the said class. Anyway, look the if, I can't think of any situation where it wouldn't be the best choice.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download