Hello;
as known HashSet store no duplicated values Unlike ArrayList, anyway i tried to make example to store Objects in HashSet and the result show it take Duplicated values
import java.util.Comparator; public class Employee{ private int id; private String name; private String address; private double salary; public Employee(int id, String name, String address, double salary) { this.id = id; this.name = name; this.address = address; this.salary = salary; } public String getAddress() { return address; } public void setAddress(String address) { 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 double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String toString(){ return "ID:" + getId() + ", Name:" + getName() + ", Address:" + getAddress() + ", Salary:" + getSalary(); } }
create Objects and add them to Set and List
import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String args[]) { Employee ts1 = new Employee (10, "Sam", "Paris", 200.0); Employee ts2 = new Employee (11, "Amal", "Berlin", 600.0); Employee ts3 = new Employee (12, "Nik", "London", 250.0); Employee ts4 = new Employee (10, "Sam", "Paris", 200.0); Employee ts5 = new Employee (14, "Jasmin", "Damas", 210.0); ArrayList<Employee> list = new ArrayList<Employee>(); list.add(ts1); list.add(ts2); list.add(ts3); list.add(ts4); list.add(ts5); System.out.println("List"); System.out.println("==================================================="); for (int i = 0; i < list.size(); i++){ System.out.println(list.get(i)); } Set<Employee> set = new HashSet<Employee>(); set.add(ts1); set.add(ts2); set.add(ts3); set.add(ts4); set.add(ts5); System.out.println(""); System.out.println("Set"); System.out.println("==================================================="); for(Employee item: set){ System.out.println(item); } } }
Output:
List =================================================== ID:10, Name:Sam, Address:Paris, Salary:200.0 ID:11, Name:Amal, Address:Berlin, Salary:600.0 ID:12, Name:Nik, Address:Lndon, Salary:250.0 ID:10, Name:Sam, Address:Paris, Salary:200.0 ID:14, Name:Jasmin, Address:Damas, Salary:210.0 Set =================================================== ID:12, Name:Nik, Address:London, Salary:250.0 ID:10, Name:Sam, Address:Paris, Salary:200.0 ID:14, Name:Jasmin, Address:Damas, Salary:210.0 ID:10, Name:Sam, Address:Paris, Salary:200.0 ID:11, Name:Amal, Address:Berlin, Salary:600.0
The same result but not the same Order, anyway how to make Hashset in this code be able to not take any duplicated Value??


LinkBack URL
About LinkBacks
Reply With Quote
