HashTable,HashMap,Properties

312 查看

HashTable,HashMap,Properties 的区别

HashMap 和 HashTable的区别

一,他们继承的父类不一样

1,HashTable继承于抽象类 Dictionary
  public class Hashtable<K,V> extends Dictionary<K,V>
2,HashMap 继承于抽象类 java.util.AbstractMap<K,V>

二,HashMap线程不安全,HashTable线程安全

HashMap:Note that this implementation is not synchronized.
如何将HashMap变成线程安全的,使用下面的方法:
 Map m = Collections.synchronizedMap(new HashMap(...));
线程不安全,非同步,一般效率相对高一些

三,HashMap 允许键,值为 null, HashTable 不可以。

 JDK:Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
 JDK:Any non-null object can be used as a key and as a value.(键,值不能为空)

三,Properties 与 HashTable 的区别

Properties 是HashTable的子类
 public class Properties
extends Hashtable<Object,Object>

并且是线程安全的,

JDK:This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization.

使用properties输出到文件

  • 资源配置文件

  • 1,.properties

    • store(OutputStream out, String comments)

  • store(Writer writer, String comments)

  • 2,.xml

    • storeToXML(OutputStream os, String comment)

  • storeToXML(OutputStream os, String comment, String encoding)

Properties pro 
          = new Properties();
    pro.setProperty("name", "mk");
    pro.setProperty("url", "www.baidu.com");
    //存储到 d盘盘符
   1,存储为.properties 文件
    pro.store(new FileOutputStream(new File("D://db.properties")), "db配置文件");
    //2,存储为 .xml文件
//    pro.storeToXML(new FileOutputStream(new File("D://db.xml")), "db配置文件");
    //使用相对路径 当前的项目根目录
//    pro.store(new FileOutputStream(new File("db.properties")), "db配置文件");    
  • 使用Properties读取资源配置文件

  • load(InputStream inStream)

  • load(Reader reader)

  • loadFromXML(InputStream in)

Properties pro 
          = new Properties();
    //读取绝对路径
    pro.load(new FileReader("D://db.properties"));
    //读取相对路径
    pro.loadFromXML(new FileInputStream("D://db.xml"));

如果文件保存在bin里面,也是在我们工作中经常碰到的一种情况

Properties pro 
          = new Properties();
    pro.load(Demo.class.getResourceAsStream("/project/db.properties"));
    pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("project/db.properties"));