Java

本类阅读TOP10

·使用MyEclipse开发Struts框架的Hello World!(录像1)
·hibernate配置笔记
·AOP编程入门--Java篇
·linux下Tomcat 5.0.20 与 Apache 2 安装/集成/配置
·在win2003下整合了整合Tomcat5.5+ apache_2.0.53+ mod_jk_2.0.47.dll
·构建Linux下IDE环境--Eclipse篇
·Jsp 连接 mySQL、Oracle 数据库备忘(Windows平台)
·ASP、JSP、PHP 三种技术比较
·Tomcat5.5.9的安装配置
·AWT GUI 设计笔记(二)

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
Encapsulation can make things change-Create a container that demostrates the "resize" of an array

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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

 




相关文章

相关软件