package com.bjsxt.others.que; import java.util.ArrayDeque; import java.util.Queue; /** * 使用隊列模擬銀行存款業務 * @author Administrator * */ public class Demo01 { /** * @param args */ public static void main(String[] args) { Queue<Request> que =new ArrayDeque<Request>(); //模擬排隊狀況 for(int i=0;i<10;i++){ final int num =i; que.offer(new Request(){ @Override public void deposit() { System.out.println("第"+num+"我的,辦理存款業務,存款額度爲:"+(Math.random()*10000)); } }); } dealWith(que); } //處理業務 public static void dealWith(Queue<Request> que){ Request req =null; while(null!=(req=que.poll())){ req.deposit(); } } } interface Request{ //存款 void deposit(); }
堆棧相關:html
package com.bjsxt.others.que; import java.util.ArrayDeque; import java.util.Deque; /** * 使用隊列實現自定義堆棧 * 一、彈 * 二、壓 * 三、獲取頭 * @author Administrator * * @param <E> */ public class MyStack<E> { //容器 private Deque<E> container =new ArrayDeque<E>(); //容量 private int cap; public MyStack(int cap) { super(); this.cap = cap; } //壓棧 public boolean push(E e){ if(container.size()+1>cap){ return false; } return container.offerLast(e); } //彈棧 public E pop(){ return container.pollLast(); } //獲取 public E peek(){ return container.peekLast(); } public int size(){ return this.container.size(); } }
Demo:java
package com.bjsxt.others.que; //測試自定義堆棧 public class Demo02 { /** * @param args */ public static void main(String[] args) { MyStack<String> backHistory =new MyStack<String>(3); backHistory.push("www.baidu.com"); backHistory.push("www.google.com"); backHistory.push("www.sina.com"); backHistory.push("www.bjsxt.cn"); System.out.println("大小:"+backHistory.size()); //遍歷 String item=null; while(null!=(item=backHistory.pop())){ System.out.println(item); } } }
Enumeration:正則表達式
package com.bjsxt.others.en; import java.util.Enumeration; import java.util.Vector; /** * Enumeration 的使用 * 一、判斷 hasMoreElements() * 二、獲取 nextElement() * * Vector 的 elements()方法 * * * @author Administrator * */ public class Demo01 { /** * @param args */ public static void main(String[] args) { Vector<String> vector =new Vector<String>(); vector.add("javase"); vector.add("html"); vector.add("oracle"); //遍歷該Vector Enumeration<String> en =vector.elements(); while(en.hasMoreElements()){ System.out.println(en.nextElement()); } } }
package com.bjsxt.others.en; import java.util.StringTokenizer; /** * Enumeration 子類 * StringTokenizer:String split() 字符串分割 * 不支持正則表達式 * * StringTokenizer(String str, String delim) * @author Administrator * */ public class Demo02 { /** * @param args */ public static void main(String[] args) { String emailStr="bjsxt@163.com;bjsxt@qq.com;bjsxt@sohu.com"; StringTokenizer token =new StringTokenizer(emailStr,";"); //遍歷獲取 while(token.hasMoreElements()){ System.out.println(token.nextElement()); } } }
HashMap與Hashtable的區別: 數組
HashTable的應用很是普遍,HashMap是新框架中用來代替HashTable的類,也就是說建議使用HashMap,不要使用HashTable。可能你以爲HashTable很好用,爲何不用呢?這裏簡單分析他們的區別。
1.HashTable的方法是同步的,HashMap未經同步,因此在多線程場合要手動同步HashMap這個區別就像Vector和ArrayList同樣。
2.HashTable不容許null值(key和value都不能夠),HashMap容許null值(key和value均可以)。
3.HashTable有一個contains(Object value),功能和containsValue(Object value)功能同樣。
4.HashTable使用Enumeration,HashMap使用Iterator。
以上只是表面的不一樣,它們的實現也有很大的不一樣。
5.HashTable中hash數組默認大小是11,增長的方式是 old*2+1。HashMap中hash數組的默認大小是16,並且必定是2的指數。
6.哈希值的使用不一樣,HashTable直接使用對象的hashCode,代碼是這樣的:
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length; 安全
首先看這兩類都實現List接口,而List接口一共有三個實現類,分別是ArrayList、Vector和LinkedList。List用於存放多個元素,可以維護元素的次序,而且容許元素的重複。3個具體實現類的相關區別以下: 多線程
查看Java源代碼,發現當數組的大小不夠的時候,須要從新創建數組,而後將元素拷貝到新的數組內,ArrayList和Vector的擴展數組的大小不一樣。 oracle
public boolean add(E e) { ensureCapacity(size + 1); // 增長元素,判斷是否可以容納。不能的話就要新建數組 elementData[size++] = e; return true; } public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; // 此行沒看出來用處,不知道開發者出於什麼考慮 int newCapacity = (oldCapacity * 3)/2 + 1; // 增長新的數組的大小 if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } }
private void ensureCapacityHelper(int minCapacity) { int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object[] oldData = elementData; int newCapacity = (capacityIncrement > 0) ? (oldCapacity + capacityIncrement) : (oldCapacity * 2); if (newCapacity < minCapacity) { newCapacity = minCapacity; } elementData = Arrays.copyOf(elementData, newCapacity); } }
Property:app
package com.bjsxt.others.pro; import java.util.Properties; /** * Properties 資源配置文件的讀寫 * 一、key 與value 只能爲字符串 * 二、存儲與讀取 * setProperty(String key, String value) * getProperty(String key, String defaultValue) * @author Administrator * */ public class Demo01 { /** * @param args */ public static void main(String[] args) { //建立對象 Properties pro =new Properties(); //存儲 pro.setProperty("driver", "oracle.jdbc.driver.OracleDriver"); //pro.setProperty("url", "jdbc:oracle:thin:@localhost:1521:orcl"); pro.setProperty("user", "scott"); pro.setProperty("pwd", "tiger"); //獲取 String url =pro.getProperty("url","test"); System.out.println(url); } }
package com.bjsxt.others.pro; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; /** * 使用Properties 輸出到文件 * 資源配置文件: * * 一、.properties * store(OutputStream out, String comments) store(Writer writer, String comments) 二、.xml storeToXML(OutputStream os, String comment) :UTF-8字符集 storeToXML(OutputStream os, String comment, String encoding) * @author Administrator * */ public class Demo02 { /** * @param args * @throws IOException * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException, IOException { //建立對象 Properties pro =new Properties(); //存儲 pro.setProperty("driver", "oracle.jdbc.driver.OracleDriver"); pro.setProperty("url", "jdbc:oracle:thin:@localhost:1521:orcl"); pro.setProperty("user", "scott"); pro.setProperty("pwd", "tiger"); //存儲到e:/others 絕對路徑 盤符: //pro.store(new FileOutputStream(new File("e:/others/db.properties")), "db配置"); //pro.storeToXML(new FileOutputStream(new File("e:/others/db.xml")), "db配置"); //使用相對路徑 當前的工程 // pro.store(new FileOutputStream(new File("db.properties")), "db配置"); // pro.store(new FileOutputStream(new File("src/db.properties")), "db配置"); pro.store(new FileOutputStream(new File("src/com/bjsxt/others/pro/db.properties")), "db配置"); } }
package com.bjsxt.others.pro; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Properties; /** * 使用Properties讀取配置文件 * 資源配置文件: * 使用相對與絕對路徑讀取 * load(InputStream inStream) load(Reader reader) loadFromXML(InputStream in) * @author Administrator * */ public class Demo03 { /** * @param args * @throws IOException * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException, IOException { Properties pro=new Properties(); //讀取 絕對路徑 //pro.load(new FileReader("e:/others/db.properties")); //讀取 相對路徑 pro.load(new FileReader("src/com/bjsxt/others/pro/db.properties")); System.out.println(pro.getProperty("user", "bjsxt")); } }
package com.bjsxt.others.pro; import java.io.IOException; import java.util.Properties; /** * 使用類相對路徑讀取配置文件 * bin * @author Administrator * */ public class Demo04 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Properties pro =new Properties(); //類相對路徑的 / bin //pro.load(Demo04.class.getResourceAsStream("/com/bjsxt/others/pro/db.properties")); //"" bin pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/bjsxt/others/pro/db.properties")); System.out.println(pro.getProperty("user", "bjsxt")); } }
java 引用分類(摘抄)框架
在 jdk 1.2 及其之後,引入了強引用、軟引用、弱引用、虛引用這四個概念。網上不少關於這四個概念的解釋,但大可能是概念性的泛泛而談,今天我結合着代碼分析了一下,首先咱們先來看定義與大概解釋(引用類型在包 java.lang.ref 裏)。 dom
一、強引用(StrongReference)
強引用不會被GC回收,而且在java.lang.ref裏也沒有實際的對應類型。舉個例子來講:
Object obj = new Object();
這裏的obj引用即是一個強引用,不會被GC回收。
二、軟引用(SoftReference)
軟引用在JVM報告內存不足的時候纔會被GC回收,不然不會回收,正是因爲這種特性軟引用在caching和pooling中用處普遍。軟引用的用法:
Object obj = new Object(); SoftReference<Object> softRef = new SoftReference(obj); // 使用 softRef.get() 獲取軟引用所引用的對象 Object objg = softRef.get();
三、弱引用(WeakReference)
當GC一但發現了弱引用對象,將會釋放WeakReference所引用的對象。弱引用使用方法與軟引用相似,但回收策略不一樣。
四、虛引用(PhantomReference)
當GC一但發現了虛引用對象,將會將PhantomReference對象插入ReferenceQueue隊列,而此時 PhantomReference所指向的對象並無被GC回收,而是要等到ReferenceQueue被你真正的處理後纔會被回收。虛引用的用法:
Object obj = new Object(); ReferenceQueue<Object> refQueue = new ReferenceQueue<Object>(); PhantomReference<Object> phanRef = new PhantomReference<Object>(obj, refQueue); // 調用phanRef.get()無論在什麼狀況下會一直返回null Object objg = phanRef.get(); // 若是obj被置爲null,當GC發現了虛引用,GC會將phanRef插入進咱們以前建立時傳入的refQueue隊列 // 注意,此時phanRef所引用的obj對象,並無被GC回收,在咱們顯式地調用refQueue.poll返回phanRef以後 // 當GC第二次發現虛引用,而此時JVM將phanRef插入到refQueue會插入失敗,此時GC纔會對obj進行回收 Reference<? extends Object> phanRefP = refQueue.poll();
看了簡單的定義以後,咱們結合着代碼來測試一下,強引用就不用說了,軟引用的描述也很清楚,關鍵是 「弱引用」 與 「虛引用」。
弱引用:
public static void main(String[] args) throws InterruptedException { Object obj = new Object(); ReferenceQueue<Object> refQueue = new ReferenceQueue<Object>(); WeakReference<Object> weakRef = new WeakReference<Object>(obj, refQueue); System.out.println(weakRef.get()); System.out.println(refQueue.poll()); obj = null; System.gc(); System.out.println(weakRef.get()); System.out.println(refQueue.poll()); }
因爲System.gc()是告訴JVM這是一個執行GC的好時機,但具體執不執行由JVM決定,所以當JVM決定執行GC,獲得的結果即是(事實上這段代碼通常都會執行GC):
java.lang.Object@de6ced
null
null
java.lang.ref.WeakReference@1fb8ee3
從執行結果得知,經過調用weakRef.get()咱們獲得了obj對象,因爲沒有執行GC,所以refQueue.poll()返回的 null,當咱們把obj = null;此時沒有引用指向堆中的obj對象了,這裏JVM執行了一次GC,咱們經過weakRef.get()發現返回了null,而 refQueue.poll()返回了WeakReference對象,所以JVM在對obj進行了回收以後,纔將weakRef插入到refQueue 隊列中。
虛引用:
public static void main(String[] args) throws InterruptedException { Object obj = new Object(); ReferenceQueue<Object> refQueue = new ReferenceQueue<Object>(); PhantomReference<Object> phanRef = new PhantomReference<Object>(obj, refQueue); System.out.println(phanRef.get()); System.out.println(refQueue.poll()); obj = null; System.gc(); System.out.println(phanRef.get()); System.out.println(refQueue.poll()); }
一樣,當JVM執行了GC,獲得的結果即是:
null
null
null
java.lang.ref.PhantomReference@1fb8ee3
從執行結果得知,咱們先前說的沒有錯,phanRef.get()無論在什麼狀況下,都會返回null,而當JVM執行GC發現虛引用以後,JVM 並無回收obj,而是將PhantomReference對象插入到對應的虛引用隊列refQueue中,當調用refQueue.poll()返回 PhantomReference對象時,poll方法會先把PhantomReference的持有隊列 queue(ReferenceQueue<? super T>)置爲NULL,NULL對象繼承自ReferenceQueue,將enqueue(Reference paramReference)方法覆蓋爲return false,而此時obj再次被GC發現時,JVM再將PhantomReference插入到NULL隊列中便會插入失敗返回false,此時GC便會回收obj。事實上經過這段代碼咱們也的卻看不出來obj是否被回收,但經過 PhantomReference 的javadoc註釋中有一句是這樣寫的:
Once the garbage collector decides that an object obj
is phantom-reachable, it is being enqueued on the corresponding queue, but its referent is not cleared. That is, the reference queue of the phantom reference must explicitly be processed by some application code.
翻譯一下(這句話很簡單,我相信不少人應該也看得懂):
一旦GC決定一個「obj」是虛可達的,它(指PhantomReference)將會被入隊到對應的隊列,可是它的指代並無被清除。也就是說,虛引用的引用隊列必定要明確地被一些應用程序代碼所處理。
弱引用與虛引用的用處
軟引用很明顯能夠用來製做caching和pooling,而弱引用與虛引用呢?其實用處也很大,首先咱們來看看弱引用,舉個例子:
class Registry { private Set registeredObjects = new HashSet(); public void register(Object object) { registeredObjects.add( object ); } }
全部我添加進 registeredObjects 中的object永遠不會被GC回收,由於這裏有個強引用保存在registeredObjects裏,另外一方面若是我把代碼改成以下:
class Registry { private Set registeredObjects = new HashSet(); public void register(Object object) { registeredObjects.add( new WeakReference(object) ); } }
如今若是GC想要回收registeredObjects中的object,便可以實現了,一樣在使用HashMap若是想實現如上的效果,一種更好的實現是使用WeakHashMap。
而虛引用呢?咱們先來看看javadoc的部分說明:
Phantom references are useful for implementing cleanup operations that are necessary before an object gets garbage-collected. They are sometimes more flexible than the finalize()
method.
翻譯一下:
虛引用在實現一個對象被回收以前必須作清理操做是頗有用的。有時候,他們比finalize()方法更靈活。
很明顯的,虛引用能夠用來作對象被回收以前的清理工做。
package com.bjsxt.others.three; import java.lang.ref.WeakReference; /** * 引用分類:強、軟、弱、虛 * 強與弱引用 * @author Administrator * */ public class RefDemo { /** * @param args */ public static void main(String[] args) { //字符串常量池 String str =new String("bjsxt is very good"); //弱引用 管理 對象 WeakReference<String> wr =new WeakReference<String>(str); System.out.println("gc運行前:"+wr.get()); //斷開引用 str =null; //通知回收 System.gc(); System.runFinalization(); //對象被回收 System.out.println("gc運行後:"+wr.get()); } public static void testStrong(){ //字符串常量池 共享(不能回收) String str ="bjsxt is very good"; //弱引用 管理 對象 WeakReference<String> wr =new WeakReference<String>(str); System.out.println("gc運行前:"+wr.get()); //斷開引用 str =null; //通知回收 System.gc(); System.runFinalization(); System.out.println("gc運行後:"+wr.get()); } }
package com.bjsxt.others.three; import java.util.WeakHashMap; /** * WeakHashMap 鍵爲弱類型,gc運行當即回收 * @author Administrator * */ public class WeakHashMapDemo { /** * @param args */ public static void main(String[] args) { WeakHashMap<String,String> map =new WeakHashMap<String,String>(); //測試數據 //常量池對象,不會回收 map.put("abc", "a"); map.put("d", "test"); //gc運行 已被回收 map.put(new String("bjsxt"), "c"); map.put(new String("dsf"), "d"); //通知回收 System.gc(); System.runFinalization(); System.out.println(map.size()); } }
package com.bjsxt.others.three; import java.util.IdentityHashMap; /** * IdentityHashMap 鍵比較地址去重 * @author Administrator * */ public class IdentityHashMapDemo { /** * @param args */ public static void main(String[] args) { IdentityHashMap<String ,String> map =new IdentityHashMap<String,String>(); //常量池中的"a" map.put("a", "a1"); map.put("a", "a2"); System.out.println(map.size()); map.put(new String("a"), "a3"); map.put(new String("a"), "a4"); System.out.println(map.size()); } }
package com.bjsxt.others.three; import java.util.EnumMap; /** * EnumMap要求鍵爲枚舉 * @author Administrator * */ public class EnumMapDemo { /** * @param args */ public static void main(String[] args) { EnumMap<Season,String> map =new EnumMap<Season,String>(Season.class); //存放值 map.put(Season.SPRING, "春困"); map.put(Season.SUMMER, "夏無力"); map.put(Season.AUTUMN, "秋乏"); map.put(Season.WINTER, "冬眠"); System.out.println(map.size()); } } //季節 enum Season{ SPRING,SUMMER,AUTUMN,WINTER }
package com.bjsxt.others.synread; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 使用Collections管理同步 容器 * synchronizedList() synchronizedSet() synchronizedMap() * @author Administrator * */ public class Demo01 { /** * @param args */ public static void main(String[] args) { List<String> list =new ArrayList<String>(); list.add("a"); list.add("b"); //list能夠同步 List<String> synList =Collections.synchronizedList(list); System.out.println("線程安全的list製做完畢"); } }
package com.bjsxt.others.synread; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * 只讀設置 * emptyXxx() 空的不可變的集合 * 一、emptyList() * emptyMap() * emptySet() 二、singletonXxx() 一個元素不可變的集合 singleton(T o) singletonList(T o) singletonMap(K key, V value) 三、unmodifiableXxx() 不可變容器 unmodifiableList(List<? extends T> list) unmodifiableSet(Set<? extends T> s) unmodifiableMap(Map<? extends K,? extends V> m) * @author Administrator * */ public class Demo02 { /** * @param args */ public static void main(String[] args) { Map<String,String> map =new HashMap<String,String>(); map.put("test", "test"); map.put("bjsxt", "bjsxt"); //只讀控制 Map<String,String> map2 =Collections.unmodifiableMap(map); //map2.put("a", "a"); //不能操做 System.out.println(map2.size()); //一個元素的容器測試 List<String> list =Collections.singletonList(new String()); list.add("test"); //list.add("bjsxt"); //只能包含一個元素的容器 } public static Set<String> oper(Set<String> set){ if(null==set){ return Collections.EMPTY_SET; //外部獲取避免NullPointerException } //操做 return set; } }