ArrayList
ArrayList是一個採用型別參數的泛型類,例如ArrayList<Employee>,這是一個儲存有Employee類型對象的泛型數組列表。
構造器:
ArrayList<Employee> staff = new ArrayList<Employee>();
下面是一個ArrayList的例子,實現了泛型數組列表的構造器,add方法,remove方法,set方法等等。
package com.xujin;import java.util.ArrayList;public class Main{public static void main(String...args){ArrayList<Employee> staff = new ArrayList<Employee>(10);//add方法添加元素staff.add(new Employee("Bob", 4000));staff.add(new Employee("Jim", 5000));staff.add(new Employee("July", 8000));staff.add(new Employee("Aliy", 6000));Employee e = staff.get(0);System.out.println(e.toString());//com.xujin.Employee[name = Bob, salary = 4000.0]//set方法將某個元素設定,該元素必須是已存在的staff.set(0, new Employee("Lily", 10000));System.out.println(staff.get(0));//com.xujin.Employee[name = Lily, salary = 10000.0]System.out.println(staff.size());//4//把數組列表削減到當前尺寸staff.trimToSize();//remove函數實現刪除一個元素staff.remove(0);System.out.println(staff.get(0));//com.xujin.Employee[name = Jim, salary = 5000.0]System.out.println(staff.size());//3//add方法插入一個元素,index為3,說明3以及3之後的所有元素都後移一位staff.add(3, new Employee("Ted", 6000));for(Employee em: staff){System.out.println(em);}/* * com.xujin.Employee[name = Jim, salary = 5000.0]com.xujin.Employee[name = July, salary = 8000.0]com.xujin.Employee[name = Aliy, salary = 6000.0]com.xujin.Employee[name = Ted, salary = 6000.0]*/}}class Employee{public Employee(String name, double salary){this.name = name;this.salary = salary;}public String toString(){return getClass().getName() + "[name = " + name + ", salary = " + salary + "]";}//定義變數private double salary;private String name;}
對象封裝器與自動打包
每個基礎資料型別 (Elementary Data Type)都有一個與之對應的類,這些類稱為對象封裝器類。
對象封裝器類:Integer,Double,Float,Long,Short,Byte,Character,Void,Boolean。註:紅色的派生於Number類。
自動打包(autoboxing):
list.add(3);//自動變成:;list.add(new Integer(3));
自動拆包:
Integer n = 3;n++;
以上兩條語句將實現:編譯器自動將Integer類型的對象n拆開,然後進行自增運算,最後再將結果打包到對象包內。
另外Integer還有幾個常用的靜態方法,比如下例中的parseInt方法
package com.xujin;public class Main{public static void main(String...args){Integer a = 1000000;System.out.println(a.intValue());//1000000int x = Integer.parseInt("124324");int y = Integer.parseInt("2333", 8);System.out.println("x:" + x + "\ny:" + y);//x:124324 y:1243}}
枚舉類
package com.xujin;public class Main{public static void main(String...args){Size s = (Size)Enum.valueOf(Size.class, "SMALL");//values方法返回該枚舉類所有的枚舉值Size[] values = Size.values();for(Size size: values){System.out.println(size.getAbb());}//ordinal()方法返回枚舉常量的位置,從0開始System.out.println(Size.LARGE.ordinal());//2}}enum Size{//這個類有五個執行個體,分別是以下五個SMALL("S"),MIDIUM("M"),LARGE("L"),EXTRA_LARGE("XL");private Size(String abbreviation){this.abbreviation = abbreviation;}public String getAbb(){return abbreviation;}private String abbreviation;}