hashmap和hashtable的区别|
有一天我去面试,面试官问我什么情况下使用hashmap而不是hashtable会出现问题? 意思是给出一个例子,其中 hashtmap 使用会导致问题,但使用 hashtable 将解决问题。
他告诉我运行代码的机器是单核的!
我给出了一个例子
Time Thread1 Thread 2
t0 tb.put("a",1)
t1 tb.put("a",2) int a = tb.get("a");
,我告诉如果在 t1 时刻 t1 和 t2 同时执行,那么就会导致问题。 他说既然是单核cpu就永远不会并行执行2条语句
有人能澄清一下什么时候会出现问题吗? 有情况举例吗?
编辑:我通过交互 hashmap 和 hashtable 发布了这个问题。我知道 hashtable 方法是同步的,而 hashmap 方法不是同步的,我已经告诉他
为了体验我实现了以下内容。并且代码从未崩溃?我不使用哈希表,但它仍然是 A 中的哈希图:)
public class MyT extends Thread {
HashMap<String,String > a = A.t;
@Override
public void run() {
while (true) {
a.put("a", "one");
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) {
MyT t1 = new MyT();
t1.start();
MyT t2 = new MyT();
t2.start();
}
}
Possible Duplicate:
Differences between HashMap and Hashtable?
I went to an interview the other day interviewer asked me under which situation will there be a problem to use hashmap rather then hashtable?
Meaning give a eg where hashtmap use will result in problem but using hashtable will resolve the problem.
He told me that the machine in which the code is run is single core!!
I gave a eg
Time Thread1 Thread 2
t0 tb.put("a",1)
t1 tb.put("a",2) int a = tb.get("a");
I told that if at t1 if both t1 and t2 executes simultaniously then it will result in problem.
He said that since it is a single core cpu it will never execute 2 statements in parallel
Can someone please clarify that , when will there be a problem?
Any example of situation?
EDIT:I posted the question by interchaing hashmap and hashtable.I know that hashtable method are synchronized and that of hashmap are not and i had told it to him
To experient i implemted following.And the code never crashed? I dint use hashtable but still it t is a hashmap in A :)
public class MyT extends Thread {
HashMap<String,String > a = A.t;
@Override
public void run() {
while (true) {
a.put("a", "one");
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) {
MyT t1 = new MyT();
t1.start();
MyT t2 = new MyT();
t2.start();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(5)
这是一个很好的链接,您可以参考:HashMap 和 Hashtable 之间的区别?
我想知道他们是否完全按照你说的那样问你,因为他似乎想问哪个是线程安全的,哪个不是。
Hashtable
是线程安全的,但为什么他会问 Hashtable
的问题?
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我认为你在提问之前必须先做以下事情:
通过以上两种方法得到以下结果:
StackOverflow : HashMap 和 Hashtable 的区别?
Google
HashMap 和 Hashtable 有什么区别
HashMap和HashTable的区别?我们可以使 hashmap 同步吗?
希望有帮助:)
I think you have to do the following things first before asking:
The following results are obtained by above two methods:
StackOverflow: Differences between HashMap and Hashtable?
Google
what is the difference between HashMap and Hashtable
Difference between HashMap and HashTable? Can we make hashmap synchronized?
Hope that helps :)