Reputation: 117
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?
Upvotes: 1
Views: 51660
Reputation: 21
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.
Upvotes: 1
Reputation: 3020
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:
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";
}
}
}
Upvotes: 0
Reputation: 1234
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.
Upvotes: 0
Reputation: 12363
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 !
Upvotes: 0
Reputation: 31699
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.
Upvotes: 1
Reputation: 1101
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
Upvotes: 0
Reputation: 6550
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
Upvotes: 2
Reputation: 803
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.")
}
}
Upvotes: 3