Java基礎之:集合——Map——HashTable
HashTable簡單介紹
-
This class implements a hash table[該類實作hashtable]
-
which maps keys to values [元素是鍵值對]
-
Any non-null object can be used as a key or as a value [hashtable的鍵和值都不能為null]
-
所以是從上面看,hashTable 基本上和hashMap一樣的.
-
hashTable 是執行緒安全的,hashMap 是執行緒不安全的.
簡單使用案例
package class_Map;
import java.util.Hashtable;
public class ClassTest03_HashTable {
?
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
Hashtable table = new Hashtable();// ok
table.put("john", 100); // ok
// table.put(null, 100); //錯誤 , 鍵不能為 null, 拋出例外
// table.put("john", null);//錯誤 , 值不能為 null, 拋出例外
table.put("lucy", 100);// ok
table.put("lic", 100);// ok
System.out.println(table);
}
}
HashTable與HashMap對比

Properties
Properties是繼承了HashTable的子類,主要用于檔案io流當中,
使用Properties讀取檔案
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
?
public class Properties01 {
?
public static void main(String[] args) {
?
// 創建一個 Properties 物件, 按照 key-value 來進行管理的
Properties prop = new Properties();
// 對檔案操作
try {
// 功能,將 a.properites 檔案讀取
// 讀取屬性檔案a.properties
// 檔案編程內容,你們 1 day 講解
// 創建一個 InputStream, 就可以讀取 a.properties
// in 的編譯型別 InputStream, 運行型別 BufferedInputStream
InputStream in = new BufferedInputStream(new FileInputStream("src\\my.properties"));
prop.load(in); /// 加載屬性串列
?
// 泛型<String>
Iterator<String> it = prop.stringPropertyNames().iterator();
// 迭代器讀取
while (it.hasNext()) {
String key = it.next();
/*
*
* user=hsp pwd=123456 ip=192.168.11.11
*/
System.out.println(key + ":" + prop.getProperty(key));
}
// 關閉流
in.close();
?
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
?
}
}
使用Properties寫檔案
import java.io.FileOutputStream;
import java.util.Properties;
?
public class Properties02 {
?
public static void main(String[] args) {
// TODO Auto-generated method stub
// 創建一個 Properties 物件, 按照 key-value 來進行管理的
Properties prop = new Properties();
try {
?
/// 保存屬性到a.properties檔案
// 創建了一個 FileOutputStream 物件,用于向檔案中 a.properties 寫入內容
FileOutputStream oFile = new FileOutputStream("src\\my.properties", true);// true表示追加打開
prop.setProperty("db", "order"); //增加
//
//prop.store(oFile, "The New properties file");
prop.store(oFile, ""); //如果是空串就沒有多余資訊了..
oFile.close();
?
} catch (Exception e) {
// TODO: handle exception
System.err.println(e.getMessage());
}
System.out.println("操作成功~~");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/241202.html
標籤:Java

