在Java中注册对象字段值
我最近开始用Java编程,我想知道是否有一种方法可以注册(比如放入数组或其他东西)某些对象字段值 在这种情况下,例如,创建对象的所有“名称”值(私有最终字符串名称) 任何帮助都将不胜感激在Java中注册对象字段值,java,class,object,constructor,field,Java,Class,Object,Constructor,Field,我最近开始用Java编程,我想知道是否有一种方法可以注册(比如放入数组或其他东西)某些对象字段值 在这种情况下,例如,创建对象的所有“名称”值(私有最终字符串名称) 任何帮助都将不胜感激 public class Item { private int amount; private double price; private final String name; private final String type; private final String
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;
}
没有什么可以阻止您向类中添加一些静态
Set
成员,这些成员将包含所创建实例的所有name
s
在项
构造函数中,可以将名称
添加到此集合
public class Item {
private int amount;
private double price;
private final String name;
private final String type;
private final String madeIn;
private static Set<String> registeredNames = new HashSet<String>();
Item(int amount, double price, String name, String type, String madeIn)
{
registeredNames.add (name); // you should consider what you want to do
// if the same name is passed to two instances
// perhaps throw an exception
this.amount=amount;
this.madeIn=madeIn;
this.name=name;
this.type=type;
this.price=price;
}
}
公共类项目{
私人整数金额;
私人双价;
私有最终字符串名;
私有最终字符串类型;
私人最终字符串madeIn;
私有静态集registeredNames=new HashSet();
项目(整数金额、双倍价格、字符串名称、字符串类型、字符串格式)
{
你应该考虑你想做什么。
//如果将相同的名称传递给两个实例
//也许会抛出一个例外
这个。金额=金额;
this.madeIn=madeIn;
this.name=name;
this.type=type;
这个。价格=价格;
}
}
只需创建一个静态的名称列表
,然后继续在构造函数中添加它,如:
private final static List<String> names = new LinkedList<String>();
public Item(..) {
names.add(name);
}
private final static List name=new LinkedList();
公共物品(……){
名称。添加(名称);
}
在集合
系列中有许多Java数据结构,如列表
或集合
。您还可以使用Map
及其子类创建关联(键/值)集合
试图在问题的行与行之间阅读,您可能希望有一些项目的集合,您希望通过那里name
字段访问这些项目
假设名称
在项
中是唯一的,并且您有属性的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
}
Map itemsByName=newhashmap();
//放一些物品。。。
itemsByName.put(item1.getName(),item1);
itemsByName.put(item2.getName(),item2);
//等等。。。
//正在查找知道其名称的项目
String key=“Foo”;
ItemItemFound=itemsByName.get(键);
if(itemFound==null){
System.out.println(“没有名称为“+键”的项);
}
否则{
//用你找到的东西做点什么
}
您可以添加一些示例吗?@DevGambit当然可以,请参见编辑。您还需要一些静态方法来访问registeredNames
集,除非您只打算在内部使用它。感谢您的时间和帮助。