如何通过引用它的另一个变量来实例化该变量?例如:
List<String> list1 = null;
List<String> list2 = list1;
如何使用 list2 实例化 list1
?我知道 list1
可以很容易地用 list1 = new ArrayList();
实例化。但我想知道的是,在上述情况下是否可以使用 list2 实例化 list1?
只是为了澄清:我想要实现的是访问 list1。我有一个包含 list1
的类,我需要修改 list1
的值。不幸的是,该类没有为 list1
提供 setter,并且 list1
仍然为 null。
public class Class1
{
private List<String> list1 = null;
public List getList1()
{
return list1; //value of list1 is null.
}
}
public class Class2
{
public static void main(String[] args)
{
Class1 class1 = new Class1();
// then I need to set the value of list1.
// However, list1 did not provide a setter method
// so my only way to access it is using a reference.
// with the code below I am assuming that I can
// create a reference to list1 and set its value.
// How do I set the value of list1?
List<String> list2 = class1.getList1();
}
}
最佳答案
我认为您要问的是是否有某种使用list2
间接初始化list1
的方法。在 Java 中,更改 list1
值的唯一方法是为其赋值。
在 Java 中,代码执行后 list2
将为 null
。与 C++(或 C)不同,Java 没有对引用的引用(或对指针的指针),因此无法使用 list2
来间接初始化 list1
。
关于java - 如何使用另一个变量实例化一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12613657/