Just as with object mutability, you need to be aware of array mutability. First look this example below.
public class ShippingInfo {
private static final String[] states = {
"AK", "AZ", "CA", "DE", "NV", "NY"};
}
The following code fragment could be used to iterate through the list of states and print them out.
for (int i = 0; i < ShippingInfo.states.length; i++) {
System.out.println(ShippingInfo.states[i]);
}
This is easy enough, but using the final keyword with arrays can be tricky. The following code does not
compile as you might expect.
ShippingInfo.states = new String[50];
It fails because you cannot assign values to final variables. The following code, however, is perfectly legal:
ShippingInfo.states[5] = "Java City";
This code replaces the entry for ("NV") with "Java City." Obviously, final arrays are not
immutable, and passing them around can violate encapsulation. No syntax in the Java programming language
provides a truly immutable array. This can lead to all kinds of inconsistencies. To avoid these problems, one
solution is to make the following changes:
1. Make the array private.
2. Add a getStates method.
3. Return a copy of the states array from the getStates method.
OR
you can use Iterator as inner class to increase the performance of the program.
Example:
public class ShippingInfo {
private static final String[] states = {
"AK", "AZ", "CA", "DE", "NV", "NY"};
public static Iterator getStates() {
return new StateIterator();
}
public static class StateIterator implements Iterator {
private int current = 0;
/* from Iterator */
public boolean hasNext() {
return current < states.length;
}
/* from Iterator */
public Object next() {
return nextState();
}
/* from Iterator */
public void remove() {
throw new UnsupportedOperationException();
}
/* custom typesafe next */
public String nextState() {
if (current < states.length) {
String state = states[current];
current++;
return state;
} else {
throw new NoSuchElementException();
}
}
}
}
The following code snippet can be used to iterate through the array safely, without concern that it could be accidentally damaged as read only.
Iterator iter = ShippingInfo.getStates();
while (iter.hasNext()) {
System.out.println(iter.next());