It is generally belived that once an array has been initialized, its size is unmodifiable. This concept is right.
But through composition, so called “Encapsulation”, we can make it possible to “change” the size of an array by changing its reference.
As we all know, Java has a quite different mechanism from C++ does that it has no pointer but references which are used to point at Objects and when you change the reference, the Object of it won't be modified.
When you say:
String a=“a“;
String b=“b“;
String c=b;
and then:
b=a;
the result is:
a=“a“;
b=“a“;
c=“b“;
Because b points to Object that reference “a“ is pointing to. And no Ojbect was changed.
So, we can “change” an array's length by changing its reference:
String[] str1={“0“,“1“,“2“};
String[] str2=new String[4];
System.arraycopy(0,str1,0,str2,str1.length);
str1=str2;
and now, str1 has one more element to use;
The following program demostrates this:
import java.util.*;
//make an container encapsulating an array of String that can be resized
public class Ex12 {
int index=0;
private String[] str;
private List list;
public Ex12(int size) {
str=new String[size];
}
public Ex12() {
str=new String[10];
}
public void add(String s) {
if(index<str.length)
str[index++]=s;
else {
String[] str2=new String[str.length+1];
System.arraycopy(str,0,str2,0,str.length);
str2[index++]=s;
//just change the object that str refers to
str=str2;//now str's length is "increased"
}
}
//get element i of the array
public String get(int i) {
return str[i];
}
//get the size of the array
public int size() {
return str.length;
}
public String toString() {
StringBuffer sb=new StringBuffer("[ ");
int i=0;
while(i<str.length-1) {
sb.append(str[i]+", ");
i++;
}
sb.append(str[str.length-1]+" ]");
return sb.toString();
}
public static void main(String[] args) {
Ex12 e=new Ex12(20);
for(int i=0;i<20;i++) {
e.add(Integer.toString(i));
}
//No Exception will be thrown
e.add("This is 21st element");
e.add("No ArrayIndexOutOfBoundsException");
System.out.println(e);
}
}