假设我有一个包含多个私有(private)字符串变量的类:
public class Children
{
private String child0, child1;
}
我想创建一个 SetName 方法,它将 child0 或 child1 设置为指定值
所以我可以在实例化 Children 类后做这样的事情:
myChildren.SetName(child0, "Lucy");
如何在方法中传递私有(private)类变量 String ?如何编写 SetName 方法的代码?我知道我可以创建一个数组,并传递元素编号,但这不是我需要的,也不是我想要实现的方式。
最佳答案
您可以将子项存储在 Map
的实现之一中。 HashMap
适用于大多数情况。
public class Children
{
private Map<String, String> children = new HashMap<String, String>();
public void SetName(string child, string name)
{
children.put(child, name);
}
}
关于java - 将内部变量作为方法中的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6155950/