Reputation:
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;
}
}
}
Upvotes: 1
Views: 1762
Reputation: 393781
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();
}
Upvotes: 3
Reputation: 8354
Person
is an inner class of Main
and since it's not static main
can't access it.
Upvotes: 1