Java中常用的集合类、ArrayList 、HashMap及其遍历方法

时间:2022-09-03 14:11:31

1 Java中常用的集合类

Java中常用的集合类、ArrayList 、HashMap及其遍历方法

Java中常用的集合类、ArrayList 、HashMap及其遍历方法

2 ArrayList (类似:动态数组)

ArrayList al = new ArrayList();
Clerk clerk1 = new Clerk("宋江", 23, 2000);
Clerk clerk2 = new Clerk("吴用", 21, 1000);
al.add(clerk1);
al.add(clerk2);
al.remove(1);

System.out.println(al.size());

for (int i = 0; i < al.size(); i++) {
Clerk cl = (Clerk) al.get(i);
System.out.println(cl.getName());
}

3 HashMap

Clerk cl1 = new Clerk("name", 12, 1200);

HashMap hm = new HashMap();

hm.put("s001", cl1);

if(hm.containsKey("s001")) {

hm.get("s001");
}

Iterator it = hm.keySet().iterator(); // 使用迭代器遍历

while (it.hasNext()) {

String key = it.next().toString();

Clerk cl = (Clerk) hm.get(key);

System.out.println(cl.getName());
}

System.out.println(hm.size());

4 各种集合遍历方法

// List
for(Employee emp: department.getEmpList()) {
System.out.println(department.getName() + " " + emp.getName());
}
// Set
for(Employee emp: department.getEmpSet()) {
System.out.println(department.getName() + " " + emp.getName());
}
// Map
for(Entry<String, Employee> entry: department.getEmpMap().entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue().getName());
}