Encapsulation can make things change-Create a container that demostrates the "resize" of an array

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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);

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航