Skip to content

Instantly share code, notes, and snippets.

@dwivedi
Created January 21, 2013 07:40
Show Gist options
  • Save dwivedi/4584310 to your computer and use it in GitHub Desktop.
Save dwivedi/4584310 to your computer and use it in GitHub Desktop.
This is the minimized code to remove the duplicacy from Generic Type Data Class
package com;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
public class Foo {
public static void main(String args[]) {
ArrayList<User> usersList = new ArrayList<User>();
usersList.clear();
User user = new User();
user.setName("A");
user.setId("1"); // duplicate
usersList.add(user);
user = new User();
user.setName("A");
user.setId("1"); // duplicate
usersList.add(user);
user = new User();
user.setName("AB");
user.setId("2"); // duplicate
usersList.add(user);
user = new User();
user.setName("C");
user.setId("4");
usersList.add(user);
user = new User();
user.setName("A");
user.setId("1"); // duplicate
usersList.add(user);
user = new User();
user.setName("A");
user.setId("2"); // duplicate
usersList.add(user);
Collection<User> userList = new HashSet<User>(usersList);
for (User userObject : userList) {
System.out.println(" Name :" + userObject.getName() + "\n Id :"
+ userObject.getId() + "\n");
}
}
}
class User {
private String name;
private String id;
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param id
* the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the id
*/
public String getId() {
return id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment