Hashtable的用法:基本用法,排序及同步
Hashtable是继承的Dictionary类,实现了Map
Hashtable<Integer,String> hashtable = new Hashtable<>();
hashtable.put(1,"aa");
hashtable.put(4,"dd");
hashtable.put(2,"bb");
hashtable.put(3,"cc");
System.out.println(hashtable);
添加null位key或value
hashtable.put(null,"xx");
kye=null时抛出异常:Exception in thread "main" java.lang.NullPointerException
hashtable.put(5,null);
value=null时仍然抛出异常。
所以key和value都不能为null。
根据key获取value
System.out.println(hashtable.get(1));//aa
删除entry
remove(key):删除成功(存在key),返回被删除的key对应的value,否则返回null。
remove(key,value):删除成功(存在entry),返回true,否则返回false
System.out.println(hashtable.remove(1));//aa
System.out.println(hashtable.remove(2,"bb"));//true
遍历
遍历很简单,获取迭代器遍历即可。
Iterator<Integer> iterator = hashtable.keySet().iterator();
while (iterator.hasNext()){
Integer key = iterator.next();
System.out.println(key+"="+hashtable.get(key));
}
排序
对于以下hashtable排序:
Hashtable<Integer,String> hashtable = new Hashtable<>();
hashtable.put(1,"aa");
hashtable.put(4,"dd");
hashtable.put(2,"bb");
hashtable.put(3,"cc");
System.out.println(hashtable);
输出:{4=dd, 3=cc, 2=bb, 1=aa}
有序的?否。只是个巧合。
Hashtable<Integer,String> hashtable = new Hashtable<>();
hashtable.put(1,"aa");
hashtable.put(4,"dd");
hashtable.put(2,"bb");
hashtable.put(3,"cc");
System.out.println(hashtable);
输出:{4=dd, 3=cc, 200=bb, 1=aa}
这样就不是有序的了,方便测试。
两种排序方法:
- Collections.sort排序
List<Map.Entry<Integer,String>> list = new ArrayList<>(hashtable.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, String>>() {
@Override
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
for (Map.Entry entry : list){
System.out.println(entry.getKey()+"="+entry.getValue());
}
在用这种方法排序时,只将keySet放入list然后在使用Collections.sort排序无效,不知为何。只有将entrySet放入list在排序才有效,而hashmap则可以只将keySet放入list排序得到有序的key即可。
- 利用TreeMap
TreeMap<Integer,String> treeMap = new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
treeMap.putAll(hashtable);
System.out.println(treeMap);
多线程中使用测试
hashtable是同步的可以直接用于多线程中。但是在迭代输出时,仍需要手动同步,否则抛出异常。
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
hashtable.put(i, "value" + i);
try {
Thread.sleep(new Random().nextInt(1));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (hashtable) {//迭代必须同步
if (hashtable.size() > 0) {
for (Map.Entry entry : hashtable.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
//System.out.println(hashtable.get(500));
}
try {
Thread.sleep(new Random().nextInt(10));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();