How do I instantiate a variable via another variable which is referencing it? For example:
List<String> list1 = null;
List<String> list2 = list1;
How do I instantiate list1 using list2? I know that list1 can easily be instantiated with list1 = new ArrayList();. But what I want to know is if it is possible to instantiate list1 using list2 given the case above?
Just for clarification: What I want to achieve is to have an access to list1. I have a class which contains list1 and I need to modify the value of list1. unfortunately, that class did not provide a setter for list1 and list1 is still 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();
}
}
I think that what you’re asking is if there is some indirect way of initializing
list1by usinglist2. In Java, the only way to change the value oflist1is to assign something to it.In Java,
list2will benullafter your code executes. Unlike C++ (or C), Java does not have references to references (or pointers to pointers), there is no way thatlist2can be used to indirectly initializelist1.