WEB开发网
开发学院WEB开发Jsp 利用基本数组类型搭建可自扩展的数组类 阅读

利用基本数组类型搭建可自扩展的数组类

 2008-01-05 10:54:07 来源:WEB开发网   
核心提示:public class ChenqiArray {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubRisingsoftArray raOne=new RisingsoftArray(

  public class ChenqiArray {
  
  /**
  * @param args
  */
  public static void main(String[] args) {
  // TODO Auto-generated method stub
  RisingsoftArray raOne=new RisingsoftArray();
  int newLength=raOne.getArrayCount()+10;
  for(int i=0;i<newLength;i++){
  raOne.setItem(i,new Integer(i));
  System.out.PRintln("raOne.items["+i+"]="+raOne.getItem(i));
  }
  newLength=raOne.getArrayCount()+5;
  for(int i=0;i<newLength;i++){
  raOne.setItem(i,new Integer(i));
  System.out.println("raOne.items["+i+"]="+raOne.getItem(i));
  }
  newLength=raOne.getArrayCount()+5;
  raOne.setItem(newLength-1,new Integer(newLength-1));
  for(int i=0;i<raOne.getArrayCount();i++){
  System.out.println("raOne.items["+i+"]="+raOne.getItem(i));
  }
  }
  }
  
  class RisingsoftArray{
  private Object[] obj;
  //constrUCtor
  public RisingsoftArray(int ArrayLength){
  if(ArrayLength>=1){
  obj=new Object[ArrayLength];
  }
  }
  public RisingsoftArray(){
  this(0);
  }
  public RisingsoftArray(Object[] obj){
  this.obj=RisingsoftArray.cloneArray(obj);
  }
  //get the Array items count
  public int getArrayCount(){
  return (obj!=null)?obj.length:0;
  }
  //auto eXPand the Array and copy the items
  public void expandArray(int n){
  if(n>0 && n>getArrayCount()){
  Object[] newObj=new Object[n];
  for(int i=0;i<getArrayCount();newObj[i]=obj[i++]){}
  obj=newObj;
  }
  }
  //get access
  public Object getItem(int pos){
  return (pos>=0 && pos<getArrayCount())?obj[pos]:null;
  }
  //set access
  public void setItem(int pos,Object obj){
  if(pos>=0 && pos<getArrayCount()){
  this.obj[pos]=obj;
  }
  else if (pos>0(pos==getArrayCount())) {
  expandArray(pos+1);
  setItem(pos,obj);
  }
  }
  //clone a Array
  public static Object[] cloneArray(Object[] obj){
  if(obj.length<1){
  return null;
  }
  else{
  Object[] newObj=new Object[obj.length];
  for(int i=0;i<obj.length;newObj[i]=obj[i++]){}
  return newObj;
  }
  }
  }

Tags:利用 基本 数组

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接