java—通过调用数组的对象名从数组中删除和删除对象

46scxncf  于 2021-07-07  发布在  Java
关注(0)|答案(2)|浏览(349)

我有一个阵列电话[]电话=新电话[5]
我创建了一个新的电话,我在阵列中发送

Telephone tel1 = new Telephone("jim","bush","1234567",0);
Telephone tel2 = new Telephone("joe","bush","1111111",0);
Telephone tel3 = new Telephone("jane","bush","4444444",0);

现在数组是这样的

Telephones = [tel1, tel2, tel3, null, null]

我想删除tel2不是使用它的索引,而是它的对象名tel2。因为随着时间的推移,tel2将在数组中移动位置,所以我将不再知道它的索引。有办法吗?

qxsslcnc

qxsslcnc1#

创建 List 数组外:

List<Telephone> list = new ArrayList<>(Arrays.asList(Telephones));

如果你已经覆盖了 equals 中的方法 Telephone ,您可以移除电话,例如。

list.remove(tel2);

快速演示:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        String[] arr = { "Hello", "Hi", "Bye", "Ok", "Thanks" };
        System.out.println(Arrays.toString(arr));// Get a list out of array

        List<String> list = new ArrayList<>(Arrays.asList(arr));
        list.remove("Ok");
        System.out.println(list);

        String[] updated = list.toArray(new String[0]);// Get an array out of list
        System.out.println(Arrays.toString(updated));
    }
}

输出:

[Hello, Hi, Bye, Ok, Thanks]
[Hello, Hi, Bye, Thanks]
[Hello, Hi, Bye, Thanks]
2lpgd968

2lpgd9682#

我认为你应该使用 Map 拿着这些 Telephone .

public final class Telephone {

    private final UUID uuid = UUID.randomUUID();
    private final String firstName;
    private final String lastName;
    private final String phone;
    private final int code;

    public Telephone(String firstName, String lastName, String phone, int code) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.phone = phone;
        this.code = code;
    }

    public UUID UUID() {
        return uuid;
    }
}
// create a telephone
Telephone tel1 = new Telephone("jim", "bush", "1234567", 0);
Telephone tel2 = new Telephone("joe", "bush", "1111111", 0);
Telephone tel3 = new Telephone("jane", "bush", "4444444", 0);

// create and keep a phone book
Map<UUID, Telephone> phoneBooks = new HashMap<>();

// add telephone to the phone book by unique key
phoneBooks.put(tel1.UUID(), tel1);
phoneBooks.put(tel2.UUID(), tel2);
phoneBooks.put(tel3.UUID(), tel3);

// remove telephone from the phone book by unique key
phoneBooks.remove(tel1.UUID());

相关问题