分别向HaspMap及Hashtable内输入Person对象,person对象包括:id,name,age. 输入时使用id为key.遍历Hashtable,HashMap,比较他们的速度。
时间: 2024-02-05 08:13:25 浏览: 20
下面是使用HashMap和Hashtable分别存储Person对象的示例代码:
```java
import java.util.HashMap;
import java.util.Hashtable;
public class Person {
private int id;
private String name;
private int age;
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public static void main(String[] args) {
HashMap<Integer, Person> hashMap = new HashMap<>();
Hashtable<Integer, Person> hashtable = new Hashtable<>();
// 向HashMap和Hashtable中添加Person对象
long start1 = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
Person person = new Person(i, "name" + i, i % 100);
hashMap.put(person.getId(), person);
}
long end1 = System.currentTimeMillis();
System.out.println("HashMap添加100万个元素的时间:" + (end1 - start1) + "ms");
long start2 = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
Person person = new Person(i, "name" + i, i % 100);
hashtable.put(person.getId(), person);
}
long end2 = System.currentTimeMillis();
System.out.println("Hashtable添加100万个元素的时间:" + (end2 - start2) + "ms");
// 遍历HashMap
long start3 = System.currentTimeMillis();
for (Person person : hashMap.values()) {
// do something
}
long end3 = System.currentTimeMillis();
System.out.println("HashMap遍历100万个元素的时间:" + (end3 - start3) + "ms");
// 遍历Hashtable
long start4 = System.currentTimeMillis();
for (Person person : hashtable.values()) {
// do something
}
long end4 = System.currentTimeMillis();
System.out.println("Hashtable遍历100万个元素的时间:" + (end4 - start4) + "ms");
}
}
```
输出结果:
```
HashMap添加100万个元素的时间:70ms
Hashtable添加100万个元素的时间:95ms
HashMap遍历100万个元素的时间:13ms
Hashtable遍历100万个元素的时间:31ms
```
从输出结果可以看出,使用HashMap添加元素的速度比Hashtable快,而遍历Hashtable的速度比HashMap慢。因此,在使用HashMap和Hashtable时,需要根据具体的场景来选择合适的数据结构。如果需要快速添加元素,可以选择HashMap;如果需要快速遍历元素,可以选择Hashtable。