Java基础系列 - JAVA集合ArrayList,Vector,HashMap,HashTable等使用

时间:2023-12-14 19:35:26
package com.test4;

import java.util.*;

/**
* JAVA集合ArrayList,Vector,HashMap,HashTable等使用
*/
public class test4 {
public static void main(String[] args) {
//ArrayList异步,线程不安全,性能高 Vector同步,线程安全,性能低
//定义个ArrayList对象
ArrayList arrayList = new ArrayList();
//显示大小
System.out.println(arrayList.size());
//添加雇员
Employer employer1 = new Employer(1000, "张三", 20);
Employer employer2 = new Employer(1001, "李四", 25);
Employer employer3 = new Employer(1002, "王五", 30);
arrayList.add(employer1);
arrayList.add(employer2);
arrayList.add(employer3); System.out.println("---------foreach循环ArrayList-------------------");
//iter + tab键快捷键生成foreach代码块
for (Object item : arrayList) {
System.out.println("雇员信息:" + item.toString());
} System.out.println("---------for循环ArrayList-------------------");
//fori 快速生成for代码块
for (int i = 0; i < arrayList.size(); i++) {
System.out.println("雇员信息:" + arrayList.get(i).toString());
} System.out.println("---------获取一个雇员信息-------------------");
//获取一个对象
Employer employer = (Employer) arrayList.get(0);
System.out.println("一个雇员信息:" + employer.getName()); System.out.println("---------显示ArrayList大小-------------------");
//显示大小
System.out.println(arrayList.size()); System.out.println("---------HashMap使用-------------------");
/**
* HashMap使用 HashMap异步,线程不安全,性能高 HashTable同步,线程安全,性能低
*/
Map hm = new HashMap();
hm.put("1000", employer1);
hm.put("1001", employer2);
hm.put("1002", employer3);
//使用迭代器
Iterator iter = hm.keySet().iterator();
while (iter.hasNext()) {
//取出Key
String key=iter.next().toString();
//根据Key取出对象
Employer emp= (Employer) hm.get(key);
System.out.println("雇员信息:"+emp.toString());
} /**
* 控制台显示
0
---------foreach循环ArrayList-------------------
雇员信息:Employer{eid=1000, name='张三', age=20}
雇员信息:Employer{eid=1001, name='李四', age=25}
雇员信息:Employer{eid=1002, name='王五', age=30}
---------for循环ArrayList-------------------
雇员信息:Employer{eid=1000, name='张三', age=20}
雇员信息:Employer{eid=1001, name='李四', age=25}
雇员信息:Employer{eid=1002, name='王五', age=30}
---------获取一个雇员信息-------------------
一个雇员信息:张三
---------显示ArrayList大小-------------------
3
---------HashMap使用-------------------
雇员信息:Employer{eid=1002, name='王五', age=30}
雇员信息:Employer{eid=1001, name='李四', age=25}
雇员信息:Employer{eid=1000, name='张三', age=20}
*/
}
} class Employer {
public Employer(int eid, String name, int age) {
this.eid = eid;
this.name = name;
this.age = age;
} private int eid;
private String name;
private int age; public int getEid() {
return eid;
} public void setEid(int eid) {
this.eid = eid;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "Employer{" +
"eid=" + eid +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}