nize
nize

Reputation: 1032

Access inner class from other class

I have this class having an inner class

public class A {
    public class NameComparator implements Comparator<A> {
        @Override
        public int compare(A o1, A o2) {
        return o1.name.compareToIgnoreCase(o2.name);
        }
    }
...
}

And I would like to access this NameComparator class from another class C (which resides in another package than A).

Example (from C):

Collections.sort(aArrayList,A.new NameComparator());

This doesn't work. Should I move the inner class NameComparator so that it is not enclosed within the class A and rename it to something like ANameComparator? They are so closely related so it feels awkward to not put this functionality within the class A.

Upvotes: 2

Views: 2433

Answers (2)

nachokk
nachokk

Reputation: 14413

You have 2 options.

Convert your inner class into a static nested class

public static class NameComparator implements Comparator<A> 

And in C

Collections.sort(aArrayList,new A.NameComparator());

Or if you don't want to modify inner class just create an instance of A.

Collections.sort(aArrayList,new A().new NameComparator());

Upvotes: 1

ppeterka
ppeterka

Reputation: 20726

If you want to use your code like this, you need to have the inner class static:

public class A {
    public static class NameComparator implements Comparator<A> {
        @Override
        public int compare(A o1, A o2) {
        return o1.name.compareToIgnoreCase(o2.name);
        }
    }
    ...
}

Why? Because if you don't mark the inner class static, it is only valid with an instance of the outer class.

You'll have to instantiate the comparator like this to use in zour use case:

Collections.sort(aArrayList,new A.NameComparator());

Upvotes: 6

Related Questions