泛型数组列表ArrayList:
ArrayList是一个采用类型参数的泛型类,<>中指定数组保存的元素的对象类型
实例讲解:
创建一个员工类Employee,用于存放到泛型数组中,也就是<>中放的就是Employee,然后main()方法中实现存储就可以了。
1.创建Employee类,这里没什么好讲的,你应该能看懂
import java.time.LocalDate;
public class Employee {
private String name;
private double salary;
private LocalDate hireDay;
public Employee(String mName, double mSalary, int year, int month, int day) {
this.name = mName;
this.salary = mSalary;
this.hireDay = LocalDate.of(year, month, day);
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public LocalDate getHireDay() {
return hireDay;
}
public void raiseSalary(double byPercent) {
double raiseValue = salary * byPercent / 100;
salary += raiseValue;
}
}
2.创建ArrayListTest类在main()方法中实现存贮,展现的功能
import java.util.ArrayList;
public class ArrayListTest {
public static void main(String[] args) {
//fill the employeeList with the three Employee objects
ArrayList<Employee> employeeList = new ArrayList<>();
employeeList.add(new Employee("Jack", 10000, 2018, 1, 1));
employeeList.add(new Employee("Rose", 20000, 2018, 1, 1));
employeeList.add(new Employee("Mike", 30000, 2018, 1, 1));
//raise employee salary by 10%
for (Employee e : employeeList) {
e.raiseSalary(10);
}
//print out the information about the three employee objects
for (Employee ee : employeeList) {
System.out.println(
"name=" + ee.getName() + " " + "salary=" + ee.getSalary() + " " + "hireDay=" + ee.getHireDay());
}
}
}
现在我们的实例就结束了,这里我添加一个ArrayList转换成数组的简单方法
import java.util.ArrayList;
public class ArrayListTest {
public static void main(String[] args) {
.........
//print out the information about the three employee objects
for (Employee ee : employeeList) {
System.out.println(
"name=" + ee.getName() + " " + "salary=" + ee.getSalary() + " " + "hireDay=" + ee.getHireDay());
}
//使用toArray()方法可以很轻松的实现ArrayList转为数组
Employee[] array = new Employee[employeeList.size()];
employeeList.toArray(array);
System.out.println();
for (Employee eee : array)
{
System.out.println("name=" + eee.getName() + " " + "salary=" + eee.getSalary() + " " + "hireDay="
+ eee.getHireDay());
}
}
}