java - 注册对象字段值 Java

标签 java class object constructor field

我最近开始使用 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/

相关文章:

java - 如何确定是通过移动浏览器访问应用程序还是使用 Java 使用 PhoneGap 应用程序

java - 如何通过 JMX 公开 Oracle 连接池统计信息?

html - 如何使用 *ngFor 显示数据

java - 如何在没有特定对象的方法内执行instanceof?

c++ - 创建重复对象的 vector ?

java - JNI - 自动将所有新生成的线程从进程附加到 JVM?

java - 尽管所有测试都通过了,Intellij 报告断言失败

class - Swift的实例方法和类型方法的区别

python - 为什么 __init__.py 将文件夹中的所有文件作为模块导入?

class - scala类的类型参数中的冒号是什么