开发者

Sorting heterogeneous elements in arraylist

How to sort heterogeneous elements in a array-lis开发者_如何转开发t? For example,

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

Now how to sort this array-list?``


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

  • how to compare on multiple classes in java?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜