jir*_*ovo 2 java instance-variables instance
I have two classes, A and B.
B contains the instances of A. I want to return instance of A from B by its name:
class A
{
public String name;
public A (String name)
{
this.name = name;
}
}
class B
{
public A a1;
public A a2;
public A a3;
public B ()
{
this.a1 = new A ("a1");
this.a2 = new A ("a2");
this.a3 = new A ("a3");
}
public A get_A_byName (String name)
{
// Is it possible to write something like this? B will always contain only instances of A
for (A a : B.variables)
{
if (a.name.equals(name))
{
return a;
}
// Or in case A doesn't have a variable "name", can I get an A instance by its declared name in B?
if (a.getClass().getName().equals(name))
{
return a;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Is it possible to do things described in code's comments? Thanks in advance.
这或多或少是为了将密钥(在本例中为字符串)与对象配对而制作的散列图
class B
{
private HashMap<String,A> theAs=new HashMap<String,A>(); //give better name
public B ()
{
theAs.put("a1",new A ("a1")); //A probably doesn't need to keep its own name internally now, but have left it as its in your original code
theAs.put("a2",new A ("a2"));
theAs.put("a3",new A ("a3"));
}
public A get_A_byName (String name)
{
return theAs.get(name);
}
}
Run Code Online (Sandbox Code Playgroud)
在Java 7+中你不需要添加第二个<String,A>,钻石推理会做,所以在Java 7或更高版本中它将是:
private HashMap<String,A> theAs=new HashMap<>();
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
376 次 |
| 最近记录: |