java对象数组怎么删除,从数组中删除对象[java]

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?

解决方案

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.")

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值