首页 > 学院 > 开发设计 > 正文

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

2019-11-18 11:59:54
字体:
来源:转载
供稿:网友

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表