gpt4 book ai didi

java - 注册对象字段值 Java

转载 作者:行者123 更新时间:2023-12-02 08:29:14 24 4
gpt4 key购买 nike

我最近开始使用 Java 编程,我想知道是否有一种方法可以注册(如放入数组或其他东西)某些对象字段值。

在这种情况下,例如创建对象的所有“名称”值(私有(private)最终字符串名称)。

如有任何帮助,我们将不胜感激。

public class Item {
private int amount;
private double price;
private final String name;
private final String type;
private final String madeIn;

Item(int amount, double price, String name, String type, String madeIn){
this.amount=amount;
this.madeIn=madeIn;
this.name=name;
this.type=type;
this.price=price;
}

最佳答案

Collection 中有许多 Java 数据结构家人喜欢ListSet .您还有 associative(键/值)集合 Map及其子类。

尝试阅读问题中的字里行间,您可能想要集合 Item你想通过那里访问 name字段。

假设 nameItem 中是独一无二的并且您有属性的 getter:

Map<String, Item> itemsByName = new HashMap<>();

// put some items...
itemsByName.put(item1.getName(), item1);
itemsByName.put(item2.getName(), item2);
// etc...

// Looking for an item knowing its name
String key = "Foo";
Item itemFound = itemsByName.get(key);
if (itemFound==null) {
System.out.println("There is no item whose name is " + key);
}
else {
// do something with itemFound
}

关于java - 注册对象字段值 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29060783/

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