import java.util.*;
public class ArrayListTest
{
public static void main(String[] args)
{
ArrayList staff = new ArrayList();
Employee emp = new Employee("Ivan",60000,1984,10,6);
Employee emp1 = new Employee("Jack",35000,1982,8,14);
staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 15));
staff.add(new Employee("Tony Tester", 40000, 1990, 12, 15));
//使用该方法将对象添加到列表的指定位置,而不会覆盖原有 值,原有值会自动往下移动一格
staff.add(1, emp);
//使用该方法将对象添加到列表的指定位置,会覆盖原有值
staff.set(2,emp1);
//使用该方法将指定位置的对象从列表中删除,其后的对象将自动往上移一个同时调整列表大小
staff.remove(2);
//size()返回当前列表中元素的个数
System.out.println(staff.size());
for (int i = 0; i < staff.size(); i++)
{
Employee e = (Employee)staff.get(i);
e.raiseSalary(5);
}
for (int i = 0; i < staff.size(); i++)
{
Employee e = (Employee)staff.get(i);
System.out.println(e);
}
}
}
class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar =
new GregorianCalendar(year, month - 1, day);
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public String toString()
{
return getClass().getName()
+ "[name="+ name
+ ",salary="+ salary
+",hireDay="+ hireDay
+"]";
}
private String name;
private double salary;
private Date hireDay;
}
大家看后可以猜出运行结果吗?