简体   繁体   中英

Sort Arraylist by property of object

So I would like to sort everything out in my ArrayList by using the objects String Name that I have assigned to it.

So far I've read about Comparators to get what I want done. But when I implement it, I get a compile error.

I initialize it like this

private static ArrayList<PeopleInfo> infoArray = new ArrayList<PeopleInfo>();

and call the sort like this

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

and this is the Class.

public class CustomComparator implements Comparator<PeopleInfo> {
    @Override
    public int compare(PeopleInfo o1, PeopleInfo o2) {
        return o1.GetLast().compareTo(o2.GetLast());
    }
}

The error I get is "No enclosing instance of type mainClass is accessible. Must qualify the allocation with an enclosing instance of type mainClass (egxnew A() where x is an instance of MainClass)."

Not really understanding what's happening. Thanks in advance!

将Comparator类声明为静态类

public static class CustomComparator implements Comparator<PeopleInfo> {

或者,您可以在主类之外声明比较器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM