Hemanth
Hemanth

Reputation: 41

Sorting heterogeneous elements in arraylist

How to sort heterogeneous elements in a array-list? For example,

ArrayList l1 = new ArrayList(); 
l1.add(1); 
l1.add("hi"); 
l1.add(1.0f); 

Now how to sort this array-list?``

Upvotes: 3

Views: 4789

Answers (3)

DaraJ
DaraJ

Reputation: 3076

It depends on how you want them sorted. You could split the list up into new ArrayLists with a defined type, sort each one of them then concatenate them?

Something like: (pseudocode)

ArrayList<Integer> intList = new ArrayList<Integer>();
ArrayList<Integer> stringList = new ArrayList<Integer>();
// ...etc

for (Object o : list) {
  if (o.getClass().equals(Integer.TYPE))
    intList.add(o);
  else if (o.getClass().equals(String.class))
    stringList.add(o);
  // ...etc
}

sort(intList);
sort(stringList);
// ...etc

concatenate(intList, stringList, ...);

That's what I'd think you do anyway.

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114817

Define computable sorting rules. Then implement those rules in a class that implements Comparator and use

Collections.sort(l1, myComparator);  // myComparator is an instance of the class
                                     // you just implemented

Upvotes: 0

aioobe
aioobe

Reputation: 421160

You would have to implement your own Comparator which compares the least upper bound of all involved types. In this case, Object.

Related question (from yesterday):

Upvotes: 2

Related Questions