Java:分别向HaspMap及Hashtable内输入Person对象,person对象包括:id,name,age. 输入时使用id为key.遍历Hashtable,HashMap,比较他们的速度。
时间: 2024-02-15 21:02:34 浏览: 98
好的,我会为您解答这个问题。
首先,让我们来了解一下HashMap和Hashtable的区别:
1. 线程安全性:Hashtable是线程安全的,而HashMap是非线程安全的。
2. 空键值:Hashtable不允许空键值,而HashMap允许一个null键和多个null值。
3. 性能:由于Hashtable是线程安全的,因此它的性能较差,而HashMap的性能更好。
下面是使用Java代码向Hashtable和HashMap中输入Person对象,并进行遍历的示例:
```
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<Integer, Person> hashtable = new Hashtable<>();
Map<Integer, Person> hashmap = new HashMap<>();
// 向Hashtable中输入Person对象
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
Person person = new Person(i, "Person_" + i, i % 100);
hashtable.put(person.getId(), person);
}
long end = System.currentTimeMillis();
System.out.println("Hashtable put time: " + (end - start) + "ms");
// 向HashMap中输入Person对象
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
Person person = new Person(i, "Person_" + i, i % 100);
hashmap.put(person.getId(), person);
}
end = System.currentTimeMillis();
System.out.println("HashMap put time: " + (end - start) + "ms");
// 遍历Hashtable
start = System.currentTimeMillis();
for (Map.Entry<Integer, Person> entry : hashtable.entrySet()) {
int id = entry.getKey();
Person person = entry.getValue();
// do something
}
end = System.currentTimeMillis();
System.out.println("Hashtable traversal time: " + (end - start) + "ms");
// 遍历HashMap
start = System.currentTimeMillis();
for (Map.Entry<Integer, Person> entry : hashmap.entrySet()) {
int id = entry.getKey();
Person person = entry.getValue();
// do something
}
end = System.currentTimeMillis();
System.out.println("HashMap traversal time: " + (end - start) + "ms");
}
}
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 void setId(int id) {
this.id = id;
}
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;
}
}
```
在上面的代码中,我们使用了System.currentTimeMillis()方法来计算Hashtable和HashMap的put时间和traversal时间。我们可以运行代码来比较它们的速度。
总的来说,由于HashMap是非线程安全的,因此它的性能比Hashtable更好。但是,在多线程环境下,Hashtable可能比HashMap更适合。
阅读全文
相关推荐
















