服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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


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

扫描关注微信公众号