熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

利用基本數組類型搭建可自擴展的數組類

2013-11-23 18:54:46  來源: Java核心技術 

  public class ChenqiArray {
  
  /**
  * @param args
  */
  public static void main(String[] args) {
  // TODO Autogenerated method stub
  RisingsoftArray raOne=new RisingsoftArray();
  int newLength=raOnegetArrayCount()+;
  for(int i=;i<newLength;i++){
  raOnesetItem(inew Integer(i));
  Systemoutprintln(ems[+i+]=+raOnegetItem(i));
  }
  newLength=raOnegetArrayCount()+;
  for(int i=;i<newLength;i++){
  raOnesetItem(inew Integer(i));
  Systemoutprintln(ems[+i+]=+raOnegetItem(i));
  }
  newLength=raOnegetArrayCount()+;
  raOnesetItem(newLengthnew Integer(newLength));
  for(int i=;i<raOnegetArrayCount();i++){
  Systemoutprintln(ems[+i+]=+raOnegetItem(i));
  }
  }
  }
  
  class RisingsoftArray{
  private Object[] obj;
  //constructor
  public RisingsoftArray(int ArrayLength){
  if(ArrayLength>=){
  obj=new Object[ArrayLength];
  }
  }
  public RisingsoftArray(){
  this();
  }
  public RisingsoftArray(Object[] obj){
  thisobj=RisingsoftArraycloneArray(obj);
  }
  //get the Array items count
  public int getArrayCount(){
  return (obj!=null)?objlength:;
  }
  //auto expand the Array and copy the items
  public void expandArray(int n){
  if(n> && n>getArrayCount()){
  Object[] newObj=new Object[n];
  for(int i=;i<getArrayCount();newObj[i]=obj[i++]){}
  obj=newObj;
  }
  }
  //get access
  public Object getItem(int pos){
  return (pos>= && pos<getArrayCount())?obj[pos]:null;
  }
  //set access
  public void setItem(int posObject obj){
  if(pos>= && pos<getArrayCount()){
  thisobj[pos]=obj;
  }
  else if (pos>||(pos==getArrayCount())) {
  expandArray(pos+);
  setItem(posobj);
  }
  }
  //clone a Array
  public static Object[] cloneArray(Object[] obj){
  if(objlength<){
  return null;
  }
  else{
  Object[] newObj=new Object[objlength];
  for(int i=;i<objlength;newObj[i]=obj[i++]){}
  return newObj;
  }
  }
  }
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25972.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.