0

I have array of custom integers:

ArrayList<MyCustomInteger> list1 = new ArrayList<MyCustomInteger>

I need integers to be custom since i want them to hold some additional methods. Now this doesn't work for custom:

Collections.sort(list1);

How can I sort them?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
ShoulO
  • 448
  • 2
  • 7
  • 20
  • 3
    Provide a custom comparator to the overloaded sort method? Or make your MyCustomInteger class implement the Comparable interface. – Alexis C. Feb 11 '15 at 21:58
  • Make sure `MyCustomInteger` implements `Comparable` or provide a custom `Comparator`. – Luiggi Mendoza Feb 11 '15 at 22:00
  • Allow your class to implement the comparable interface. Check out this link detailing how to do it! http://www.tutorialspoint.com/java/java_using_comparator.htm – Evan Bechtol Feb 11 '15 at 22:01
  • Can't you just have your custom integer inherit from the Integer class, and thus they will be compared the same way in the list when sorting? – Malik Brahimi Feb 11 '15 at 22:17
  • @Malik , not sure how to do it - Eclipse throws error: "The type MyCustomInteger cannot subclass the final class Integer" – ShoulO Feb 11 '15 at 22:44

1 Answers1

1

Your MyCustomInteger class must implement the Comparable interface. Alternatively, you have to pass a Comparator instance to the sort method.

Read these:

Community
  • 1
  • 1