gpt4 book ai didi

java - 在Java中创建具有唯一id的列表并对其进行操作

转载 作者:行者123 更新时间:2023-12-01 17:55:47 25 4
gpt4 key购买 nike

我想创建一个程序来创建一个如下所示的列表

ID: 1
Name: Example
Surname: Example
email: example

//New list

ID: 2
Name: Example
Surname: Example
email: example

然后当我想更改某些内容(例如名称:)时,我想通过 id 更改它,因此只能在 ID 为 2 的列表内更改它

最佳答案

您应该使用HashMap

创建一个包含 ID、姓名、姓氏和电子邮件实例变量的类(让我们将其命名为 YourClass)。

然后创建一个 HashMap,其中键是标识符,值为 YourClass:

Map<Integer,YourClass> map = new HashMap<>();
map.put(objectOfYourClassWithID1.getID(),objectOfYourClassWithID1);
map.put(objectOfYourClassWithID2.getID(),objectOfYourClassWithID2);
if (map.containsKey(2)) {
map.get(2).setSomeProperty(newValue); // this will only change the object whose ID is 2
}

关于java - 在Java中创建具有唯一id的列表并对其进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44994526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com