// How to eliminate duplicate user defined objects from HashSet?
package collectctiondemo;
public class Student {
private int id;
private String name;
private String address;
public Student(int id, String name, String address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
================================================================================
package collectctiondemo;
import java.util.HashSet;
import java.util.Set;
import collectctiondemo.Student;
public class StudentMain {
public static void main(String[] args) {
Set<Student> s=new HashSet<Student>();
Student s1=new Student(101, "govind", "noida");
Student s2=new Student(101, "govind", "noida");
Student s3=new Student(102, "khan", "newashoknagar");
Student s4=new Student(101, "govind", "noida");
s.add(s1);
s.add(s1);
s.add(s2);
s.add(s3);
s.add(s4);
for(Student p:s)
{
System.out.println(p.getId()+" "+p.getName()+" "+p.getAddress());
}
}
}
===============================================================================
o/p:-----------------------------
101 govind noida
102 khan newashoknagar
No comments:
Post a Comment