1

My program asks the user to enter the first name, last name and age of 5 people and stores them in an array. I want to write a method that asks the user whom they want to delete from the array and then deletes that employee. I know in arrays you cannot technically delete an object from an array, just replace it. This is what I've done so far:

private void deleteEmployee(){

       Scanner scan = new Scanner(System.in);
       System.out.println("Enter the first name of the employee you want to delete from the list")
      String name = scan.nextLine();

       for (int i = 0; i < employees.length; i++) {
           if (employees[i].getFirstName().equals(name)){
               employees[i] = employees[employees.length - 1];
             break; 
           }

           if (i == employees.length - 1) {
               System.out.println("That requested person is not employed at this firm.")
       }


}

My problem is that it does not decreases the array size by 1, it just replaces the person I want to delete with the last person in my array. My output has the last employee in the array repeated twice (in it's last index and in the index of the person I wanted to delete) How do I fix this?

Mitesh Pathak
  • 1,306
  • 10
  • 14
user3452963
  • 117
  • 2
  • 4
  • 15
  • 2
    Can you use mutable collections like a linked list or is the array a requirement? – Mark W Mar 28 '14 at 17:00
  • 1
    Well, you can't really delete an element from an array, like you said. Best you can hope for is to give the removed element a null value instead. Thus leaving it empty. Or, you could alternatively, make a new array with length-1 elements and copy all desired elements to that array. – ViRALiC Mar 28 '14 at 17:01
  • You can't change the size of an array once you declare it. You should go with something like an array list. – Pranava Sheoran Mar 28 '14 at 17:03
  • If you don't mind having nulls in your array, set employees[i] to null, not to the last employee. This will help to avoid duplication. – ursus Mar 28 '14 at 17:04

8 Answers8

3

you can replace the employee with null whenever want to delete it. when inserting a new emplyee, you can first look at a null index and place it.

private void deleteEmployee(){

  Scanner scan = new Scanner(System.in);
  System.out.println("Enter the first name of the employee you want to delete from the list")
  String name = scan.nextLine();

  for (int i = 0; i < employees.length; i++) {
       if (employee[i] != null && employees[i].getFirstName().equals(name)){
           employees[i] = null;
         break; 
       }

       if (i == employees.length - 1) {
           System.out.println("That requested person is not employed at this firm.")
  }
}
Chamil
  • 805
  • 5
  • 12
  • when printing out all the first names, last names and ages of everyone in the array, the program crashes at the location I replaced with a null. Why is that? – user3452963 Mar 28 '14 at 17:14
  • What do you mean "crashes"--does it throw `NullPointerException`? If so, that means you have to check and make sure it isn't null before trying to get data from it. – ajb Mar 28 '14 at 17:19
  • yes, it was a NullPointerException. But I fixed it like you suggested. Thanks. – user3452963 Mar 28 '14 at 17:54
  • One more question, if i wanted to add all the ages of the ages of employees in the array (excluding the null one) how will I do this? keep in my mind that i do not know the array size before hand so I cannot iterate through and find the null one and add the rest. Or can I? – user3452963 Mar 28 '14 at 21:47
2

You may want to use ArrayLists for this problem. ArrayLists are Java's way of creating a mutable array. With arraylists, the array can be automatically expanded and reduced based on the number of objects in the Array.

You can add and delete objects using the index or variable name.

Sample Code:

ArrayList<Employee> employees = new ArrayList<>;

Then you can use the following methods:

employees.remove(int index);
employees.remove(Object o);

Check this out for more reference: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Jake Chasan
  • 6,290
  • 9
  • 44
  • 90
1

One possibility: although you can't change the actual length of the array, you can use another variable to keep track of the "real" length (i.e. the number of elements in the array that you know are valid):

  int currentLength = employees.length;
  for (int i = 0; i < currentLength; i++) {
       if (employees[i].getFirstName().equals(name)){
           employees[i] = employees[currentLength - 1];
           // employees[currentLength - 1] = null;   ... could help reclaim storage
           currentLength--;
         break; 
       }

       if (i == currentLength - 1) {
           System.out.println("That requested person is not employed at this firm.")
   }

The program just "knows" that array elements from employees[currentLength] through employees[employees.length - 1] aren't meaningful. You could also set those meaningless elements to null so that there aren't unused references that could prevent some objects from being garbage-collected (this would be important in a larger program). This approach can be a bit error-prone, because you have to remember to use currentLength instead of employees.length. Overall, I think it's better to use an ArrayList, which has a way to delete elements.

ajb
  • 31,309
  • 3
  • 58
  • 84
1

The length of an array in Java can not be changed, it's initialized when you create it. And you can not manual delete a element immediately(like C++). You can set it to null, then wait for the JVM to recycle it.

For convenience, you can use List collection in java.util package. They are convenient for remove/add elements.

0

I suggest you make use of ArrayList, it already had the remove method. That method also make the size of the list reduce by number of removed items

VinhNT
  • 1,091
  • 8
  • 13
0

Hi things will be simpler for you if you use an ArrayList instead of an array, Here is how your code will look like assuming that you have a EmployerClass implementing the getFirstName() method

List<EmployerClass> employees = new ArrayList<EmployerClass>();
// Here is the new type of your employees pool

....
// do whatever you want to put employees in the poll using employees.add(...)

private void deleteEmployee(){

       Scanner scan = new Scanner(System.in);
       System.out.println("Enter the first name of the employee you want to delete from the list")
       String name = scan.nextLine();

       EmployerClass tmpEmployer = null;

       for(EmployerClass emp : employees) {
           if(emp.getFirstName().equals(name)) {            
               break;
           }
       }

       if(tmpEmployer != null){
         // remove the employee to the pool
         employees.remove(tmpEmployer);

       } else {

         System.out.println("That requested person is not employed at this firm.");

       }        
}

good luck !

Fopa Léon Constantin
  • 11,863
  • 8
  • 48
  • 82
0

You can't really delete it, but you can only make it null.

ArrayList or LinkedList is better for this task. In both you can use builtin methods to add or remove elements and size is handle automatically.

Alley Shairu
  • 1,234
  • 1
  • 7
  • 11
0

There are some points:

(1) Java array(use the symbol "[]") is a fixed size structure. It means you must specify the size(length) of the array when you create it. Like this:

int[] intArray = new int[10];

The purpose of the specific size is to tell Java compiler to allocate memory. Array is allocated in contiguous memory. Once the allocation has been done, its size could not be changed.(You can image there are other data "behind" the array, if the array is extende, will overlap the other data.)

(2) If you want to get a flexible data collection, for your adding/removing, you can use ArrayList or LinkedList. These Java built-in collections can be extended by themselves if needed. What's more:

  • ArrayList is implemented by Java array, it will automatically create a new larger array and copy the data into it when its Capacity is not enough. It has good performance in loop, access elements by index.
  • LinkedList is implemented by Linked List. It has good performance in insert/remove elements.
  • For Both lists, if you want to use the remove(Object o) correctly, you have to implement your object's public boolean equals(Object) function.

Ref to the code:

import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;

public class ListTest {

    public static void main(String[] args) {
        List<Employee> employees = new LinkedList<Employee>();
//      List<Employee> employees = new ArrayList<Employee>();
        // Add 3 employees
        employees.add(new Employee("Tom", "White", 10));
        employees.add(new Employee("Mary", "Black", 20));
        employees.add(new Employee("Jack", "Brown", 30));
        // See what are in the list
        System.out.println(employees);
        // Remove the 2nd one.
        employees.remove(new Employee("Mary", "Black", 20));
        // See what are in the list after removing.
        System.out.println(employees);
    }

static class Employee {     
    private String firstName;
    private String lastName;
    private int age;

    public Employee(String firstName, String lastName, int age) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if(super.equals(obj)) {
            return true;
        }
        else {
            if(obj.getClass() == Employee.class) {
                Employee that = (Employee)obj;
                return firstName.equals(that.getFirstName()) && lastName.equals(that.getLastName()) && (age == that.getAge());
            }
            else {
                return false;
            }
        }
    }

    @Override
    public String toString() {
        return "Employee [firstName=" + firstName + ", lastName="
                + lastName + ", age=" + age + "]\n";
    }

}

}
yellowB
  • 2,900
  • 1
  • 16
  • 19