1

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 (e.g. x.new A() where x is an instance of MainClass)."

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

3
  • 1
    Where are you getting this error?? Where is your PeopleInfo class?? And which is your MainClass?? Commented Oct 6, 2012 at 8:06
  • 1
    The problem does not seem to be in the code you have shown. Commented Oct 6, 2012 at 8:07
  • Possible duplicate of Java - No enclosing instance of type Foo is accessible Commented Mar 4, 2016 at 0:25

2 Answers 2

3

Declare your Comparator class as a static class

public static class CustomComparator implements Comparator<PeopleInfo> {

Sign up to request clarification or add additional context in comments.

4 Comments

Gaaah, something so simple. Mind explaining why :)?
There seems to be a fairly decent explanation here, with links to further info: stackoverflow.com/questions/70324/…
@KelseyAbreu: without the static keyword when declaring an inner class - it (the inner class) must have an "attached" instance of the enclosing class. So, you cannot use it (easily) in static methods (such as main(String[])). When using the static keyword, you let the compiler know it does not need an instance of the enclosing class, and is actually behaving like a normal not nested class.
Thanks! Some of the most obvious things happen when learning new languages.
0

Alternatively you can declare comparator outside main class.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.