- package text;
- import java.util.ArrayList;
- import java.util.List;
- public class SxtArrayList{private Object[] elementData;
- private int size;
- public int size(){
- return size;
- }
- public boolean isEmpty(){
- return size ==0;
- }
- public SxtArrayList(){
- this(10);
- }
- public SxtArrayList(int initialCapacity){ // 构造器
- if(initialCapacity<0){
- try{
- throw new Exception();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- elementData= new Object[initialCapacity];
- }
- public void add(Object obj){
- // 数组扩容
- if(size==elementData.length){
- Object[] newArray= new Object[size*2+1];
- // System.arraycopy(elementData,0,newArray,0,elementData.length);
- for(int i=0;i<elementData.length;i++){
- newArray[i]=elementData[1];
- }
- elementData= newArray;
- }
- elementData[size]=obj;
- size++;
- }
- public Object get(int index){
- if(index<0||index>=size){
- try{
- throw new Exception();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- return elementData[index];
- }
- public void remove(int index){
- if(index<0||index>=size){
- try{
- throw new Exception();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- int numMoved=size-index-1;
- if(numMoved>0){
- System.arraycopy(elementData,index+1,elementData,index,numMoved);
- }
- elementData[--size]=null;
- }
- public void rangeCheck(int index){
- if(index<0||index>=size){
- try{
- throw new Exception();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
- // public void remove(Object obj){
- // for(int i=0;i<size;i++){
- // if(get(i).equals(obj)){// 注意: 底层调用的 equals 方法, 不是 ==
- // remove(i);
- // }
- // }
- // }
- public Object set(int index,Object obj){
- rangeCheck(index);
- Object oldValue= elementData[index];
- elementData[index]=obj;
- return oldValue;
- }
- public static void main(String[] args){
- SxtArrayList list2=new SxtArrayList(3);
- list2.add("222");
- list2.add("222");
- list2.add("222");
- list2.add("222");
- list2.add("222");
- list2.add("222");
- System.out.println(list2.size);
- Object str2=list2.get(5);
- System.out.println(str2);
- list2.remove(2);
- System.out.println(list2.size);
- }
- }
来源: http://www.bubuko.com/infodetail-2625627.html