Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Duplicate Entries in Array - Java

For Java practice, I am trying to create a method inside my EmployeesDirectory Class that:

  • Removes Duplicate entries from the array
  • The array should be the same length after removing duplicates
  • Non-Empty entries should be making a contiguous sequence at the beginning of the array - and the actualNum should keep a record of the entries

Duplicate Means: Same Name, Position and Salary

Here is my Current Code:

I am unsure on how to implement this - any help would be appreciated

class EmployeeDirectory {

    private Employee dir[];
    private int size;
    private int actualNum;

    public EmployeeDirectory(int n) {
        this.size = n;
        dir = new Employee[size];
    }

    public boolean add(String name, String position, double salary) {
        if (dir[size-1] != null) {
            dir[actualNum] = new Employee(name, position, salary);
            actualNum++;
            return true;
        } else {
            return false;
        }
    }
}
like image 412
RandomMath Avatar asked May 09 '15 16:05

RandomMath


People also ask

How to remove duplicate elements of an array in Java?

How to remove duplicate elements of an array in java? To detect the duplicate values in an array you need to compare each element of the array to all the remaining elements in case of a match you got your duplicate element.

How do you remove duplicates from a sorted array in Python?

Removing duplicates from a sorted array If array elements are sorted already then removing duplicates involve following steps: Create a new array 'tempArray' with same size as original array 'origArray'. Iterate over array starting from index location ‘0’.

How to print and display elements in an array that are duplicated?

Print and display elements in an array that are duplicated using add (element) method. Print and display elements in an array after removing duplicates from it. Getting size of TreeSet using size () method.

Should array length be the same after removing duplicates and empty entries?

The array should be the same length after removing duplicates Non-Empty entries should be making a contiguous sequence at the beginning of the array - and the actualNum should keep a record of the entries I am unsure on how to implement this - any help would be appreciated


1 Answers

I'd rather you did not write a distinct method for removing duplicates. If I were you, I would search for duplicates in add method and then instantly decide whether I need to add Employee.

Also, why don't you use Sets (link for HashSet) instead of arrays for your purpose? Sets by their own definition disallow adding duplicates, so they seem to be appropriate as a solution

like image 150
Lysenko Andrii Avatar answered Oct 11 '22 00:10

Lysenko Andrii