zoukankan      html  css  js  c++  java
  • Write a program to implement ArrayList

    Write a program to implement your own ArrayList class. It should contain add(), get(), remove(), size() methods. Use dynamic array logic. It should increase its size when it reaches threshold. 

    import java.util.Arrays;
     
    public class MyArrayList {
     
        private Object[] myStore;
        private int actSize = 0;
         
        public MyArrayList(){
            myStore = new Object[10];
        }
         
        public Object get(int index){
            if(index < actSize){
                return myStore[index];
            } else {
                throw new ArrayIndexOutOfBoundsException();
            }
        }
         
        public void add(Object obj){
            if(myStore.length-actSize <= 5){
                increaseListSize();
            }
            myStore[actSize++] = obj;
        }
         
        public Object remove(int index){
            if(index < actSize){
                Object obj = myStore[index];
                myStore[index] = null;
                int tmp = index;
                while(tmp < actSize){
                    myStore[tmp] = myStore[tmp+1];
                    myStore[tmp+1] = null;
                    tmp++;
                }
                actSize--;
                return obj;
            } else {
                throw new ArrayIndexOutOfBoundsException();
            }
             
        }
         
        public int size(){
            return actSize;
        }
         
        private void increaseListSize(){
            myStore = Arrays.copyOf(myStore, myStore.length*2);
            System.out.println("
    New length: "+myStore.length);
        }
         
        public static void main(String a[]){
            MyArrayList mal = new MyArrayList();
            mal.add(new Integer(2));
            mal.add(new Integer(5));
            mal.add(new Integer(1));
            mal.add(new Integer(23));
            mal.add(new Integer(14));
            for(int i=0;i<mal.size();i++){
                System.out.print(mal.get(i)+" ");
            }
            mal.add(new Integer(29));
            System.out.println("Element at Index 5:"+mal.get(5));
            System.out.println("List size: "+mal.size());
            System.out.println("Removing element at index 2: "+mal.remove(2));
            for(int i=0;i<mal.size();i++){
                System.out.print(mal.get(i)+" ");
            }
        }
    }
  • 相关阅读:
    共享一个从字符串转 Lambda 表达式的类(2)
    多个文件上传控件
    使用 SQL的 for xml path来进行字符串拼接
    数据结构之双向链表
    我的收藏颜色代码表
    C++中的字节对齐分析
    收藏sina播放器嵌入代码
    弃用数据库自增ID,曝光一下我自己用到的解决方法之终结篇
    google工作原理图
    easyicon一个非常好用的找图标的网站
  • 原文地址:https://www.cnblogs.com/hygeia/p/5165050.html
Copyright © 2011-2022 走看看