Skip to main content

Making a Set in Java to avoid duplicates for complex data types

For simple data types, Set will work to avoid the duplicates using the Object class equals() and hashcode() methods, but to utilize the same behavior for the complex data types, we have to override the hashcode()  and equals() methods as shown in the below example:



package core.collections;
import java.util.HashSet;
import java.util.Set;


/*If a set of different Employee type objects having variables first name and last name as a members and two of the employee type objects having same first name and last name how can you avoid the duplicate employee objects ? and if you print the size of the set what will be the output ?*/

public class EmployeeCompare {

    public static void main(String[] args) {
        Set<Employee> employees = new HashSet<Employee>();
        employees.add(new Employee("Kalyan Valluru"));
        employees.add(new Employee("Rani Marthala"));
        employees.add(new Employee("Kalyan Valluru"));

        System.out.println("Employees Count is: "+employees.size());
        System.out.println(employees);
    }

}

class Employee{

    private String fullName;

    public Employee(String fullName){
        this.fullName = fullName;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    @Override
    public String toString() {
        return this.fullName;
    }

    @Override
     public int hashCode() {
        return this.fullName.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        Employee other = (Employee) obj;
        if (!fullName.equals(other.fullName))
            return false;
        else
            return true;
    }

}


Comments

Post a Comment

Popular posts from this blog

Solution Repeated String Hacker Rank

Challenge: Lilah has a string,  , of lowercase English letters that she repeated infinitely many times. Given an integer,  , find and print the number of letter  a 's in the first   letters of Lilah's infinite string. For example, if the string   and  , the substring we consider is  , the first   characters of her infinite string. There are   occurrences of  a  in the substring. Function Description Complete the  repeatedString  function in the editor below. It should return an integer representing the number of occurrences of  a  in the prefix of length   in the infinitely repeating string. repeatedString has the following parameter(s): s : a string to repeat n : the number of characters to consider Input Format The first line contains a single string,  . The second line contains an integer,  . Constraints For   of ...