我的java學習日記(12)

java學習第十二節之集合

一、           數組容器的優化

  publicclass Vector {

      privateObject[] objs = null;

      privateint index = 0;

   //寫一個addAll方法,添加數組

      publicvoid addAll(Object[] objs) {

             for(Object object : objs) {

                    add(object);

             }

      }

   //寫一個add方法,給數組添加元素

      publicvoid add(Object obj) {

             if(objs == null) {

                    objs= new Object[5];

                    objs[0]= obj;

                    index++;

             }else {

        //下邊該方法優於for循環

                    if(index == objs.length) {

                           Object[]objs1 = new Object[(int) (objs.length * 1.5)];

                           System.arraycopy(objs,0, objs1, 0, objs.length);

                           objs= objs1;

                    }

                    objs[index]= obj;

                    index++;

             }

      }

   //寫一個size方法,返回數組下標

      publicint size() {

             returnindex;

      }

   //一個get方法,獲得數組下標

      publicObject get(int index) throws IndexOutOfBoundsException {

             if(index >= this.index) {

                    thrownew IndexOutOfBoundsException(index + "");

             }

             returnobjs[index];

      }

    //remove方法,刪除第i個元素

      publicvoid remove(int i) {

             if(i >= index || i < 0) {

                    thrownew IndexOutOfBoundsException(index + "");

             }

             //Object objs1=new Object();

             System.arraycopy(objs,i + 1, objs, i, objs.length - i - 1);

             index--;

      }

}

二、           Scanner的使用

  importjava.util.Scanner;

public class Test {

      publicstatic void main(String[] args) {

             Scanners = new Scanner(System.in);             

             //int index=s.nextInt();

             //System.out.println(index);

 

             Stringline = s.nextLine();

             System.out.println(line);

      }

 }

三、           簡易ATM

大概思路是創建一個AtmIf接口,裏面的方法有取錢、存錢、查詢,並用AtmIm類實現。本人正在研究,有想法的歡迎交流下。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章