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)
4
  • need clarification, please edit and provide more details about the classes and attributes Commented Apr 28, 2016 at 8:47
  • 1
    Do your classes implement a common interface? if not, why not? Commented Apr 28, 2016 at 8:49
  • Try using Comparator or check this. Commented Apr 28, 2016 at 8:50
  • 1
    Do the classes A, B, C and D share a common parent-class? If yes, you could use a Comparator<Parent> to sort them by Sequence. Here is an example of how a Comparator is used to order an Employee-object by Salary.. Commented Apr 28, 2016 at 8:50

1 Answer 1

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.

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

Comments

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.