从数组中删除一个对象 [java]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22718898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:28:33  来源:igfitidea点击:

deleting an object from an array [java]

javaarrays

提问by user3452963

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:

我的程序要求用户输入 5 个人的名字、姓氏和年龄,并将它们存储在一个数组中。我想编写一个方法,询问用户要从数组中删除谁,然后删除该员工。我知道在数组中您不能从技术上删除数组中的对象,只需替换它即可。这是我到目前为止所做的:

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?

我的问题是它不会将数组大小减少 1,它只是用数组中的最后一个人替换我想删除的人。我的输出使数组中的最后一个员工重复了两次(在它的最后一个索引和我想删除的人的索引中)我该如何解决这个问题?

采纳答案by Chamil

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.

每当想要删除它时,您都可以用 null 替换该员工。插入新员工时,可以先看一个空索引并放置。

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

回答by Jake Chasan

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.

您可能想使用 ArrayLists 来解决这个问题。ArrayLists 是 Java 创建可变数组的方式。使用数组列表,可以根据数组中对象的数量自动扩展和减少数组。

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

查看更多参考:http: //docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

回答by VinhNT

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

我建议你使用 ArrayList,它已经有了 remove 方法。该方法还使列表的大小减少了已删除项目的数量

回答by ajb

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 nullso 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 currentLengthinstead of employees.length. Overall, I think it's better to use an ArrayList, which has a way to delete elements.

该计划只是“知道”这个数组元素employees[currentLength]通过employees[employees.length - 1]是没有意义的。您还可以将那些无意义的元素设置为 ,null以便没有未使用的引用会阻止某些对象被垃圾收集(这在较大的程序中很重要)。这种方法可能有点容易出错,因为您必须记住使用currentLength代替employees.length。总的来说,我认为最好使用ArrayList,它有一种删除元素的方法。

回答by Fopa Léon Constantin

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

嗨,如果您使用 anArrayList而不是 an array,事情对您来说会更简单,这是假设您有一个EmployerClass实现该getFirstName()方法的代码的样子

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 !

祝你好运 !

回答by Alley Shairu

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

你不能真正删除它,但你只能让它为空。

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

ArrayListLinkedList更适合此任务。在这两种情况下,您都可以使用内置方法来添加或删除元素,并且大小是自动处理的。

回答by yellowB

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:

(1) Java 数组(使用符号“[]”)是一个固定大小的结构。这意味着您必须在创建数组时指定数组的大小(长度)。像这样:

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

具体大小的目的是告诉Java编译器分配内存。数组在连续内存中分配。分配完成后,其大小将无法更改。(您可以想象数组“后面”还有其他数据,如果数组扩展,将与其他数据重叠。)

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

(2) 如果您想获得灵活的数据收集,添加/删除,您可以使用ArrayListLinkedList。如果需要,这些 Java 内置集合可以自行扩展。更重要的是:

  • ArrayListis implemented by Java array, it will automatically create a new larger array and copy the data into it when its Capacityis not enough. It has good performance in loop, access elements by index.
  • LinkedListis 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.
  • ArrayList由Java数组实现,当它的容量不够时,它会自动创建一个新的更大的数组并将数据复制到其中。它具有良好的循环性能,按索引访问元素。
  • LinkedListLinked List实现。它在插入/删除元素方面具有良好的性能。
  • 对于两个列表,如果要remove(Object o)正确使用它们,则必须实现对象的public boolean equals(Object)功能。

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("Hyman", "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";
    }

}

}

回答by minani huruka

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

Java 中数组的长度不能改变,它在你创建它时被初始化。并且您不能立即手动删除元素(如 C++)。您可以将其设置为 null,然后等待 JVM 回收它。

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

为方便起见,您可以使用 java.util 包中的 List 集合。它们便于删除/添加元素。