I am trying to remove the duplicate elements from ArrayList using .contains() if elements are primitive datatype it works but user-defined datatype does not work.
public class UserBean { String name; String address; 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; } } import java.util.ArrayList; import java.util.List; public class Main { public static void main(String args[]){ UserBean bean=new UserBean(); List<UserBean> userInfo=new ArrayList(); bean.setName("rob"); bean.setAddress("mumbai"); userInfo.add(bean); bean=new UserBean(); bean.setName("bob"); bean.setAddress("pune"); userInfo.add(bean); bean=new UserBean(); bean.setName("rob"); bean.setAddress("mumbai"); userInfo.add(bean); bean=new UserBean(); bean.setName("bob"); bean.setAddress("pune"); userInfo.add(bean); List<UserBean> finalList=new ArrayList(); finalList.add(userInfo.get(0)); for(UserBean temp:userInfo){ if(!finalList.contains(temp)){ finalList.add(temp); } } for(UserBean temp:finalList){ System.out.println(temp.getName()+" "+temp.getAddress()); } } }
I get following output:
rob mumbai
bob pune
rob mumbai
bob pune