I’m trying to override Variables that are already defined.
Here is my code:
package com.diesal11;
import java.lang.reflect.Array;
public class Test{
private class List {
public String[] words;
public List(String[] array) {
this.words = array;
}
}
public List[] all;
public Test() {
this.all = new List[2];
String[] array = new String[2];
array[0] = "One";
array[1] = "Two";
this.all[0] = new List(array);
array[0] = "Three";
array[1] = "Four";
this.all[1] = new List(array);
System.out.println(this.all[0].words[0]);
System.out.println(this.all[0].words[1]);
System.out.println(this.all[1].words[0]);
System.out.println(this.all[1].words[1]);
}
public static void main(String[] args) {
Test test = new Test();
}
}
The problem is the console prints out:
Three
Four
Three
Four
How can I fix this? the actual code I need this for is setup in this way so it can’t change much.
Thanks in advance!
The problem is you are storing a reference to the array passed to the List constructor.
You then change that same array and pass it to the 2nd List object.
Instead, create a new array and pass that in like this:
EDITED – Added style-related feedback
Your bigger problem is this code has lots of style issues:
List: You should avoid using class names from the JDK, especially from the Collections frameworkMyListclassstatic: It doesn’t need to access any fields from the containing classTest– it’s a DTOA simple change that avoids this problem would be this:
The syntax
String... wordsis called a “varargs” parameter – it creates an array on the fly that only the method has a reference to (although arrays can also be passed in, giving you the same problem).The only safe way is to make a copy of the array and store that, or provide a method that allows you to add a word (using a List to hold the words for example)