0

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)
wai kwan Chiu
  • 15
  • 1
  • 3
  • need clarification, please edit and provide more details about the classes and attributes – Lokesh Sanapalli Apr 28 '16 at 08:47
  • 1
    Do your classes implement a common interface? if not, why not? – khelwood Apr 28 '16 at 08:49
  • Try using `Comparator` or check [this](http://stackoverflow.com/a/25501226/4790490). – Hardik Pithva Apr 28 '16 at 08:50
  • 1
    Do the classes A, B, C and D share a common parent-class? If yes, you could use a Comparator to sort them by Sequence. [Here is an example of how a Comparator is used to order an Employee-object by Salary.](http://java2novice.com/java-collections-and-util/arraylist/sort-comparator/). – Kevin Cruijssen Apr 28 '16 at 08:50

1 Answers1

0

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.

Collections.sort

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.

Community
  • 1
  • 1
dquijada
  • 1,697
  • 3
  • 14
  • 19