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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值