Sorting ArrayList of Arraylist in java

后端 未结 7 1093
忘掉有多难
忘掉有多难 2021-01-19 03:16

I have an ArrayList of ArrayList of String.

In Outer ArrayList on each index each Inner ArrayList has four items have four parameters.

  1. Contacts Id
7条回答
  •  一个人的身影
    2021-01-19 03:49

    Comparator / Comparable Interfaces can't help because I don't have any objects.

    Incorrect. You do have objects. All of the things you are trying to sort are objects.

    If you are trying to sort the ArrayList objects in an ArrayList>, you need to implement a Comparator>. (The Comparable approach is the wrong one for this data structure. You would need to declare a custom subclass of ArrayList ... and that's yuck!)


    But a better idea would be to represent your objects with custom classes. In this case, your ArrayList of String should be a custom Contact class with 4 fields, getters and (if required) setters. Then you declare that as implementing Comparable, and implement the compareTo method.


    Other Answers show how to implement a Comparator based on just one field of the list. That may be sufficient, but it will give you a sort order where the order of a pair of different "John Smith"s would be indeterminate. (I would use a second field as a tie-breaker. The Id field would be ideal if the ids are unique.)

提交回复
热议问题