Friday, May 15, 2009

Arrays and final qualifier

One has to be careful regarding arrays which are declared final. It only means that the whole array reference itself cannot be changed to point to a different array. Individual elements of the array can be modified. I have an example below to depict this:

public class TestFinalArray {

final StringBuilder[] array;

TestFinalArray(int size, String... records) {
//Initialize final array
array = new StringBuilder[size];
for (int i = 0; i < size; i++) {
array[i] = new StringBuilder(records[i]);
}

}

public static void main(String[] args) {
TestFinalArray tfa =
new TestFinalArray(3, new String[] {"1","2", "3"});
print("Original array", tfa.array);
//Modify elements of the array
tfa.array[0] = new StringBuilder("Hello");
tfa.array[1] = tfa.array[1].append("World");
print("After Modification", tfa.array);

}

public static void print(String s, StringBuilder[] array) {
if (s != null) {
System.out.println(s);
}
for (StringBuilder elem: array) {
System.out.println(elem);
}
}

}




Output:
Original array
1
2
3
After Modification
Hello
2World
3

No comments:

Post a Comment