ArrayList
ArrayList是一个采用类型参数的泛型类,例如ArrayList<Employee>,这是一个保存有Employee类型对象的泛型数组列表。
构造器:
ArrayList<Employee> staff = new ArrayList<Employee>();
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;
}
对象包装器与自动打包
每个基本数据类型都有一个与之对应的类,这些类称为对象包装器类。
对象包装器类: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());//1000000
int 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;
}