There is a collection of 20 Student objects. You are supposed to write a method to return Student objects with distinct last names
E.g If Students are John Doe, John Lincoln, Amy Doe, Foo Bar => then output should return Student objects for John Doe, John Lincoln, Foo Bar.
This is my code. What is wrong ? It prints duplicate Student object Akshay Jain and Om Jain. As lastName is same,it should be avoided. In other cases it is giving correct output.
class Student{
private String firstName;
private String lastName;
public Student(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String firstName ) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName( String lastName ) {
this.lastName = lastName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.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 (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
@Override
public String toString() {
return "Student [firstName=" + firstName + ", lastName=" + lastName
+ "]";
}
public static void main(String[] args) {
TreeSet<Student> treeSet=new TreeSet<Student>(new MyComparator() {
});
treeSet.add(new Student("Akshay","Jain"));
treeSet.add(new Student("Akshay","Shah"));
treeSet.add(new Student("Rahul","Jain"));
treeSet.add(new Student("Prakash","Patil"));
treeSet.add(new Student("Om","Jain"));
treeSet.add(new Student("Chaitali","Mehata"));
treeSet.add(new Student("Obama","Jain"));
treeSet.add(new Student("Narendra","Jain"));
treeSet.add(new Student("Vijay","Magdum"));
treeSet.add(new Student("Hari","Patil"));
treeSet.add(new Student("Anuj","Doshi"));
treeSet.add(new Student("Arnav","Gandhi"));
treeSet.add(new Student("Abhay","Jain"));
treeSet.add(new Student("Kedar","Gandhi"));
System.out.println(treeSet);
}
}
class MyComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
if(s1.getLastName().equals(s2.getLastName()))
return 0;
else
return +1;
}
}