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!

Kelsey Abreu
  • 1,094
  • 3
  • 17
  • 42
  • 1
    Where are you getting this error?? Where is your PeopleInfo class?? And which is your MainClass?? – Rohit Jain Oct 06 '12 at 08:06
  • 1
    The problem does not seem to be in the code you have shown. – assylias Oct 06 '12 at 08:07
  • Possible duplicate of [Java - No enclosing instance of type Foo is accessible](http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible) – fabian Mar 04 '16 at 00:25

2 Answers2

3

Declare your Comparator class as a static class

public static class CustomComparator implements Comparator<PeopleInfo> {

Sameer
  • 4,379
  • 1
  • 23
  • 23
  • Gaaah, something so simple. Mind explaining why :)? – Kelsey Abreu Oct 06 '12 at 08:10
  • There seems to be a fairly decent explanation here, with links to further info: http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class – clstrfsck Oct 06 '12 at 08:16
  • @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. – amit Oct 06 '12 at 08:16
  • Thanks! Some of the most obvious things happen when learning new languages. – Kelsey Abreu Oct 06 '12 at 08:55
0

Alternatively you can declare comparator outside main class.

Satheesh Cheveri
  • 3,621
  • 3
  • 27
  • 46