문제

I'm using a public API provided by a 3rd party and I have a collection of objects that are defined as final.

The object has a method getName() which lets me retrieve the String name of the object.

What I need to do is sort the objects by name and what I tried to do initially was extend the original class to implement Comparable. But that's when I found out it was final and therefore not possible.

Apologies for the terminology here... new to Java and still finding my way. Please could you help by providing me with alternative methods?

Thanks,

도움이 되었습니까?

해결책

You can implement your own Comparator without extending the class, and use it as a parameter for Collections.sort:

public class MyComparator implements Comparator<MyClass> {
    @Override
    int compate (MyClass a, MyClass b) {
        // null handling removed for clarity's sake
        // add it if you need it
        return a.getName().compareTo(b.getName());
    }
}

And now just use it:

List<MyClass> myList = ...;
Collections.sort (myList, new MyComparator());

다른 팁

You will have to implement your own comparator and use Collections.sort for your collection. Something like this:

class CustomComparator implements Comparator<YourObject> {

    @Override
    public int compare(YourObject o1, YourObject o2) {
      return o1.getName().compareTo(o2.getName());
    }
}

Then use the Comparator as

Collections.sort(yourCollection,new CustomComparator());

Hope it helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top