Java 中的自定义 ArrayList
一个自定义 ArrayList 可以拥有多种类型的数据,其属性通常基于用户需求。
一个展示自定义 ArrayList 的程序如下所示 −
示例
import java.util.ArrayList; public class CustomArrayList { int n = 5; class Employee { int eno; String name; Employee(int eno, String name) { this.eno = eno; this.name = name; } } public static void main(String args[]) { int eno[] = {101, 102, 103, 104, 105}; String name[] = {"Jane", "Mary", "Adam", "Harry", "John"}; CustomArrayList caList = new CustomArrayList(); caList.add(eno, name); } public void add(int eno[], String name[]) { ArrayList<Employee> aList = new ArrayList<>(); for (int i = 0; i < n; i++) { aList.add(new Employee(eno[i], name[i])); } print(aList); } public void print(ArrayList<Employee> aList) { for (int i = 0; i < n; i++) { Employee e = aList.get(i); System.out.println("
Employee Number: " + e.eno); System.out.println("Employee Name: " + e.name); } } }
上述程序的输出如下 −
输出
Employee Number: 101 Employee Name: Jane Employee Number: 102 Employee Name: Mary Employee Number: 103 Employee Name: Adam Employee Number: 104 Employee Name: Harry Employee Number: 105 Employee Name: John
广告