1

How to fix below error? I need quick help.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing instance of type Main (e.g. x.new A() where x is an instance of Main).

at com.common.Main.main(Main.java:16)

Here is my code for reference. If we fixed that this issue then "John" should be printed only once and not twice. How we can restrict "John" to print once

public class Main {
    public static void main(String[] args) {
        Set<Person> l = new HashSet<Person>();
        l.add(new Person("John"));
        l.add(new Person("John"));
        l.add(new Person("Matt"));
        l.add(new Person("Deepak"));
        l.add(new Person("Chris"));

        for (Iterator iterator = l.iterator(); iterator.hasNext();) {
            Person person = (Person) iterator.next();
            System.out.println(person.getName());
      }
    }

    public class Person{
        private String name;

        public Person(String name) {
            super();
            this.setName(name);
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
  • 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 03 '16 at 23:45

2 Answers2

3

Since your Person class doesn't look like it should be an inner class (i.e. it doesn't look like it requires an associated instance of the enclosing Main class), make it static (i.e. a nested class of the Main class, which doesn't require an enclosing instance) :

public static class Person { ...

or move it outside your Main class.

EDIT :

As for your second issue, override equals and hashCode in your Person class, in order to let HashSet know when two objects should be considered identical :

public boolean equals (Object other) {
    if (!(other instanceof Person))
        return false;
    Person op = (Person) other;
    return this.name.equals(op.name);
}

public int hashCode () {
    return name.hashCode();
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thank you. Though I use set but still why John is printing twice? I only want to print it once. What should I changed. Currently the Output I am getting Chris John John Matt Deepak –  Nov 21 '15 at 08:18
  • @user4567570 That's a different issue. In order for your `HashSet` to function as you wish, you must override `equals` and `hashCode` in your `Person` class, so that two `Person` instances having the same name will be equal to each other and have the same `hashCode`. – Eran Nov 21 '15 at 08:19
1

Person is an inner class of Main and since it's not static main can't access it.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24