package com.bjsxt.others.commons; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.functors.EqualPredicate; import org.apache.commons.collections4.functors.NotNullPredicate; import org.apache.commons.collections4.functors.UniquePredicate; import org.apache.commons.collections4.list.PredicatedList; import org.junit.Test; /** 函數式編程 之 Predicate 斷言 封裝條件或判別式 if..else替代 1、 new EqualPredicate<類型>(值) EqualPredicate.equalPredicate(值); 2、NotNullPredicate.INSTANCE 3、UniquePredicate.uniquePredicate() 4、自定義 new Predicate() +evaluate PredicateUtils.allPredicate andPredicate anyPredicate PredicatedXxx.predicatedXxx(容器,判斷) * @author Administrator * */ public class Demo01 { /** * @param args */ public static void main(String[] args) { System.out.println("======自定義判斷======"); //自定義的判別式 Predicate<String> selfPre =new Predicate<String>(){ @Override public boolean evaluate(String object) { return object.length()>=5 && object.length()<=20; }}; Predicate notNull=NotNullPredicate.notNullPredicate(); Predicate all =PredicateUtils.allPredicate(notNull,selfPre); List<String> list =PredicatedList.predicatedList(new ArrayList<String>(),all); list.add("bjsxt"); list.add(null); list.add("bj"); } /** * 判斷唯一 */ public static void unique(){ System.out.println("====唯一性判斷===="); Predicate<Long> uniquePre =UniquePredicate.uniquePredicate(); List<Long> list =PredicatedList.predicatedList(new ArrayList<Long>(), uniquePre); list.add(100L); list.add(200L); list.add(100L); //出現重復值,拋出異常 } /** * 判斷非空 */ public static void notNull(){ System.out.println("====非空判斷===="); //Predicate notNull=NotNullPredicate.INSTANCE; Predicate notNull=NotNullPredicate.notNullPredicate(); //String str ="bjs"; String str =null; System.out.println(notNull.evaluate(str)); //如果非空為true ,否則為false //添加容器值的判斷 List<Long> list =PredicatedList.predicatedList(new ArrayList<Long>(), notNull); list.add(1000L); list.add(null); //驗證失敗,出現異常 } /** * 比較相等判斷 */ @Test public static void equal(){ System.out.println("======相等判斷======"); //Predicate<String> pre =new EqualPredicate<String>("bjsxt"); Predicate<String> pre =EqualPredicate.equalPredicate("bjsxt"); boolean flag =pre.evaluate("bj"); System.out.println(flag); } }
package com.bjsxt.others.commons; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.functors.SwitchTransformer; import org.junit.Test; /** 解耦,業務處理與判斷進行分類 函數式編程 Transformer 類型轉化 1、new Transformer() +transform 2、SwitchTransformer CollectionUtils.collect(容器,轉換器) * @author Administrator * */ public class Demo02 { /** * @param args */ public static void main(String[] args) { System.out.println("===自定義類型轉換=="); //判別式 Predicate<Employee> isLow=new Predicate<Employee>(){ @Override public boolean evaluate(Employee emp) { return emp.getSalary()<10000; } }; Predicate<Employee> isHigh=new Predicate<Employee>(){ @Override public boolean evaluate(Employee emp) { return emp.getSalary()>=10000; } }; Predicate[] pres ={isLow,isHigh}; //轉換 Transformer<Employee,Level> lowTrans =new Transformer<Employee,Level>(){ @Override public Level transform(Employee input) { return new Level(input.getName(),"賣身中"); }}; Transformer<Employee,Level> highTrans =new Transformer<Employee,Level>(){ @Override public Level transform(Employee input) { return new Level(input.getName(),"養身中"); }}; Transformer[] trans ={lowTrans,highTrans}; //二者進行了關聯 Transformer switchTrans =new SwitchTransformer(pres, trans, null); //容器 List<Employee> list =new ArrayList<Employee>(); list.add(new Employee("老馬",1000000)); list.add(new Employee("老裴",999)); Collection<Level> levelList = CollectionUtils.collect(list,switchTrans); //遍歷容器 Iterator<Level> levelIt =levelList.iterator(); while(levelIt.hasNext()){ System.out.println(levelIt.next()); } } /** * 內置類型的轉換 */ @Test public static void inner(){ System.out.println("===內置類型轉換 長整形時間日期,轉成指定格式的字符串=="); //類型轉換器 Transformer<Long,String> trans =new Transformer<Long,String>(){ @Override public String transform(Long input) { return new SimpleDateFormat("yyyy年MM月dd日").format(input); }}; //容器 List<Long> list =new ArrayList<Long>(); list.add(999999999999L); list.add(300000000L); //工具類 程序猿出錢---開發商---農民工出力 Collection<String> result=CollectionUtils.collect(list, trans); //遍歷查看結果 for(String time:result){ System.out.println(time); } } }
package com.bjsxt.others.commons; /** * 員工類 * @author Administrator * */ public class Employee { private String name; private double salary; //alt +/ public Employee() { } //alt+shift+s o public Employee(String name, double salary) { super(); this.name = name; this.salary = salary; } //alt+shift+s +r tab 回車 shift+tab 回車 public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override public String toString() { return "(碼農:"+this.name+",敲磚錢:"+this.salary+")"; } }
package com.bjsxt.others.commons; /** * 等級類 * @author Administrator * */ public class Level { private String name; private String level; public Level() { // TODO Auto-generated constructor stub } public Level(String name, String level) { super(); this.name = name; this.level = level; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } @Override public String toString() { return "(碼農:"+this.name+",水平:"+this.level+")"; } }
package com.bjsxt.others.commons; public class Goods { private String name; private double price; //折扣 private boolean discount; public Goods() { // TODO Auto-generated constructor stub } public Goods(String name, double price, boolean discount) { super(); this.name = name; this.price = price; this.discount = discount; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public boolean isDiscount() { return discount; } public void setDiscount(boolean discount) { this.discount = discount; } @Override public String toString() { return "(商品:"+this.name+",價格:"+this.price+",是否打折:"+(discount?"是":"否")+")"; } }
package com.bjsxt.others.commons; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.ChainedClosure; import org.apache.commons.collections4.functors.IfClosure; import org.apache.commons.collections4.functors.WhileClosure; /** 函數式編程 Closure 閉包 封裝特定的業務功能 1、Closure 2、IfClosure IfClosure.ifClosure(斷言,功能1,功能2) 3、WhileClosure WhileClosure.whileClosure(斷言,功能,標識) 4、ChainedClosure.chainedClosure(功能列表); CollectionUtils.forAllDo(容器,功能類對象); * @author Administrator * */ public class Demo03 { /** * @param args */ public static void main(String[] args) { //basic(); ifClosure(); //whileClosure(); chainClosure(); } /** * 折上減 先打折商品,進行9折,滿百再減20 */ public static void chainClosure(){ List<Goods> goodsList =new ArrayList<Goods>(); goodsList.add(new Goods("javase視頻",120,true)); goodsList.add(new Goods("javaee視頻",100,false)); goodsList.add(new Goods("高新技術視頻",80,false)); //滿百減20 Closure<Goods> subtract=new Closure<Goods>(){ public void execute(Goods goods) { if(goods.getPrice()>=100){ goods.setPrice(goods.getPrice()-20); } }}; //打折 Closure<Goods> discount=new Closure<Goods>(){ public void execute(Goods goods) { if(goods.isDiscount()){ goods.setPrice(goods.getPrice()*0.9); } }}; //鏈式操作 Closure<Goods> chainClo=ChainedClosure.chainedClosure(discount,subtract); //關聯 CollectionUtils.forAllDo(goodsList,chainClo); //查看操作后的數據 for(Goods temp:goodsList){ System.out.println(temp); } } /** * 確保所有的員工工資都大於10000,如果已經超過的不再上漲 */ public static void whileClosure(){ //數據 List<Employee> empList =new ArrayList<Employee>(); empList.add(new Employee("bjsxt",20000)); empList.add(new Employee("is",10000)); empList.add(new Employee("good",5000)); //業務功能 每次上漲0.2 Closure<Employee> cols=new Closure<Employee>(){ public void execute(Employee emp) { emp.setSalary(emp.getSalary()*1.2); }}; //判斷 Predicate<Employee> empPre=new Predicate<Employee>(){ @Override public boolean evaluate(Employee emp) { return emp.getSalary()<10000; } }; //false 表示 while結構 先判斷后執行 true do..while 先執行后判斷 Closure<Employee> whileCols =WhileClosure.whileClosure(empPre, cols, false); //工具類 CollectionUtils.forAllDo(empList, whileCols) ; //操作后的數據 Iterator<Employee> empIt=empList.iterator(); while(empIt.hasNext()){ System.out.println(empIt.next()); } } /** * 二選一 如果是打折商品,進行9折,否則滿百減20 */ public static void ifClosure(){ List<Goods> goodsList =new ArrayList<Goods>(); goodsList.add(new Goods("javase視頻",120,true)); goodsList.add(new Goods("javaee視頻",100,false)); goodsList.add(new Goods("高新技術視頻",80,false)); //滿百減20 Closure<Goods> subtract=new Closure<Goods>(){ public void execute(Goods goods) { if(goods.getPrice()>=100){ goods.setPrice(goods.getPrice()-20); } }}; //打折 Closure<Goods> discount=new Closure<Goods>(){ public void execute(Goods goods) { if(goods.isDiscount()){ goods.setPrice(goods.getPrice()*0.9); } }}; //判斷 Predicate<Goods> pre=new Predicate<Goods>(){ public boolean evaluate(Goods goods) { return goods.isDiscount(); }}; //二選一 Closure<Goods> ifClo=IfClosure.ifClosure(pre, discount,subtract); //關聯 CollectionUtils.forAllDo(goodsList,ifClo); //查看操作后的數據 for(Goods temp:goodsList){ System.out.println(temp); } } /** * 基本操作 */ public static void basic(){ //數據 List<Employee> empList =new ArrayList<Employee>(); empList.add(new Employee("bjsxt",20000)); empList.add(new Employee("is",10000)); empList.add(new Employee("good",5000)); //業務功能 Closure<Employee> cols=new Closure<Employee>(){ public void execute(Employee emp) { emp.setSalary(emp.getSalary()*1.2); }}; //工具類 CollectionUtils.forAllDo(empList, cols) ; //操作后的數據 Iterator<Employee> empIt=empList.iterator(); while(empIt.hasNext()){ System.out.println(empIt.next()); } } }
package com.bjsxt.others.commons; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.commons.collections4.CollectionUtils; /** * 集合操作 * 1、並集 * CollectionUtils.union(); * 2、交集 * CollectionUtils.intersection(); * CollectionUtils.retainAll(); * 3、差集 * CollectionUtils.subtract(); * @author Administrator * */ public class Demo04 { /** * @param args */ public static void main(String[] args) { Set<Integer> set1 =new HashSet<Integer>(); set1.add(1); set1.add(2); set1.add(3); Set<Integer> set2 =new HashSet<Integer>(); set2.add(2); set2.add(3); set2.add(4); //並集 System.out.println("=========並集============"); Collection<Integer> col =CollectionUtils.union(set1,set2); for(Integer temp:col){ System.out.println(temp); } //交集 System.out.println("=========交集============"); //col =CollectionUtils.intersection(set1, set2); col =CollectionUtils.retainAll(set1, set2); for(Integer temp:col){ System.out.println(temp); } //差集 System.out.println("=========差集============"); col =CollectionUtils.subtract(set1, set2); for(Integer temp:col){ System.out.println(temp); } } }
package com.bjsxt.others.commons; import java.util.Queue; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.NotNullPredicate; import org.apache.commons.collections4.queue.CircularFifoQueue; import org.apache.commons.collections4.queue.PredicatedQueue; import org.apache.commons.collections4.queue.UnmodifiableQueue; /** Queue隊列 1、循環隊列:CircularFifoQueue 2、只讀隊列:不可改變隊列 UnmodifiableQueue 3、斷言隊列:PredicatedQueue.predicatedQueue() * @author Administrator * */ public class Demo05 { /** * @param args */ public static void main(String[] args) { //circular(); //readOnly(); predicate(); } /** * 斷言隊列 */ public static void predicate(){ //循環隊列 CircularFifoQueue<String> que =new CircularFifoQueue<String>(2); que.add("a"); que.add("b"); que.add("c"); Predicate notNull=NotNullPredicate.INSTANCE; //包裝成對應的隊列 Queue<String> que2=PredicatedQueue.predicatedQueue(que, notNull); que2.add(null); } /** * 只讀隊列 */ public static void readOnly(){ //循環隊列 CircularFifoQueue<String> que =new CircularFifoQueue<String>(2); que.add("a"); que.add("b"); que.add("c"); Queue<String> readOnlyQue =UnmodifiableQueue.unmodifiableQueue(que); readOnlyQue.add("d"); } /** * 循環隊列 */ public static void circular(){ //循環隊列 CircularFifoQueue<String> que =new CircularFifoQueue<String>(2); que.add("a"); que.add("b"); que.add("c"); //查看 for(int i=0;i<que.size();i++){ System.out.println(que.get(i)); } } }
package com.bjsxt.others.commons; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.bidimap.DualHashBidiMap; import org.apache.commons.collections4.iterators.ArrayListIterator; import org.apache.commons.collections4.iterators.FilterIterator; import org.apache.commons.collections4.iterators.LoopingIterator; import org.apache.commons.collections4.iterators.UniqueFilterIterator; import org.apache.commons.collections4.map.HashedMap; /** 迭代器的擴展 1、MapIterator 以后不再使用map.keySet.iterator訪問 IterableMap HashedMap 2、UniqueFilterIterator 去重迭代器 3、FilterIterator 自定義過濾 +Predicate 4、LoopingIterator 循環迭代器 5、ArrayListIterator 數組迭代器 * @author Administrator * */ public class Demo06 { /** * @param args */ public static void main(String[] args) { //mapIt(); //uniqueIt(); //filterIt(); //loopIt(); arrayIt(); } /** * 數組迭代器 */ public static void arrayIt(){ System.out.println("===== 數組迭代器 ===="); int[] arr ={1,2,3,4,5}; //數組迭代器 //Iterator<Integer> it =new ArrayListIterator<Integer>(arr); //指定起始索引和結束索引 Iterator<Integer> it =new ArrayListIterator<Integer>(arr,1,3); while(it.hasNext()){ System.out.println(it.next()); } } /** * 循環迭代器 */ public static void loopIt(){ System.out.println("===== 循環迭代器 ===="); List<String> list =new ArrayList<String>(); list.add("refer"); list.add("dad"); list.add("bjsxt"); list.add("moom"); Iterator<String> it =new LoopingIterator(list); for(int i=0;i<15;i++){ System.out.println(it.next()); } } /** * 自定義迭代器 */ public static void filterIt(){ System.out.println("=====自定義迭代器 ===="); List<String> list =new ArrayList<String>(); list.add("refer"); list.add("dad"); list.add("bjsxt"); list.add("moom"); //自定義條件判斷 Predicate<String> pre =new Predicate<String>(){ public boolean evaluate(String value) { //回文判斷 return new StringBuilder(value).reverse().toString().equals(value); }}; //去除重復的過濾器 Iterator<String> it =new FilterIterator(list.iterator(),pre); while(it.hasNext()){ System.out.println(it.next()); } } /** * 去重迭代器 */ public static void uniqueIt(){ System.out.println("=====去重迭代器 ===="); List<String> list =new ArrayList<String>(); list.add("a"); list.add("b"); list.add("a"); //去除重復的過濾器 Iterator<String> it =new UniqueFilterIterator(list.iterator()); while(it.hasNext()){ System.out.println(it.next()); } } /** * map迭代器 */ public static void mapIt(){ System.out.println("=====map迭代器===="); IterableMap<String,String> map =new HashedMap<String,String>(); map.put("a","bjsxt"); map.put("b", "sxt"); map.put("c", "good"); //使用 MapIterator MapIterator<String,String> it =map.mapIterator(); while(it.hasNext()){ //一定要it.next() /* it.next(); String key =it.getKey(); */ String key =it.next(); String value =it.getValue(); System.out.println(key+"-->"+value); } } }
package com.bjsxt.others.commons; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.bidimap.DualHashBidiMap; import org.apache.commons.collections4.bidimap.DualTreeBidiMap; /** 雙向Map 要求鍵與值都不能重復 BidiMap inverseBidiMap() 1、DualTreeBidiMap :有序 2、DualHashBidiMap :無序 * @author Administrator * */ public class Demo07 { /** * @param args */ public static void main(String[] args) { //hashMap(); treeMap(); } /** * 有序的雙向Map */ public static void treeMap(){ System.out.println("=====有序的雙向Map===="); BidiMap<String,String> map =new DualTreeBidiMap<String,String>(); map.put("bj", "bj@test.com"); map.put("sxt", "sxt@qq.com"); //遍歷查看 MapIterator<String,String> it =map.inverseBidiMap().mapIterator(); while(it.hasNext()){ String key =it.next(); String value =it.getValue(); System.out.println(key+"-->"+value); } } /** * 無序的雙向Map */ public static void hashMap(){ System.out.println("=====無序的雙向Map===="); BidiMap<String,String> map =new DualHashBidiMap<String,String>(); map.put("bj", "bj@test.com"); map.put("sxt", "sxt@qq.com"); //反轉 System.out.println(map.inverseBidiMap().get("sxt@qq.com")); //遍歷查看 MapIterator<String,String> it =map.inverseBidiMap().mapIterator(); while(it.hasNext()){ String key =it.next(); String value =it.getValue(); System.out.println(key+"-->"+value); } } }
package com.bjsxt.others.commons; import java.util.Iterator; import java.util.Set; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.bag.HashBag; import org.apache.commons.collections4.bag.TreeBag; /** Bag 包 允許重復 1、HashBag 無序 2、TreeBag 有序 統計單詞的出現次數 * @author Administrator * */ public class Demo08 { /** * @param args */ public static void main(String[] args) { //hashBag(); //treeBag(); String str ="this is a cat and that is a mice where is the food"; //分割字符串 String[] strArray =str.split(" "); Bag<String> bag =new TreeBag<String>(); for(String temp:strArray){ bag.add(temp); } System.out.println("====統計次數==="); Set<String> keys =bag.uniqueSet(); for(String letter:keys){ System.out.println(letter+"-->"+bag.getCount(letter)); } } /** * 有序 */ public static void treeBag(){ System.out.println("=====有序的包===="); Bag<String> bag =new TreeBag<String>(); bag.add("a"); bag.add("a",5); bag.remove("a", 2); bag.add("b"); bag.add("c"); Iterator<String> it =bag.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } /** * 無序 */ public static void hashBag(){ System.out.println("=====無序的包===="); Bag<String> bag =new HashBag<String>(); bag.add("a"); bag.add("a",5); bag.remove("a", 2); bag.add("b"); bag.add("c"); Iterator<String> it =bag.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } }
package collection; import java.util.NoSuchElementException; /** * @author SUNHAN * @Date: 2014年9月29日 */ public class SLinkedList { private transient int size=0; private transient Node head=new Node(null,null,null);//用頭結點來表示整個鏈表 public SLinkedList(){//默認構造方法 head.next=head; head.previous=head; } public void add(Object element){//在末尾插入元素 Node Nnode=new Node(element,head,head.previous); Nnode.previous.next=Nnode; Nnode.next.previous=Nnode; size++; } public void addBefore(Object o,Node e){ Node newNode=new Node(o,e,e.previous); newNode.previous.next=newNode; newNode.next.previous=newNode; size++; } public void add(int index,Object o){//倆參數的add()方法 addBefore(o,(index==size?head:node(index))); } private Node node(int index){ if(index<0||index>=size){ throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size); } Node e=head;//從header開始循環 if(index<size/2){ for(int i=0;i<=index;i++){//對用戶而言,頭結點是不可見的 e=e.next; } } else{ for(int i=size;i>index;i--){ e=e.previous; } } return e; } public Object remove(int index){ Node e=node(index); remove(e); return e.element; } private void remove(Node e){ if(e==head){ throw new NoSuchElementException(); } e.previous.next=e.next; e.next.previous=e.previous; size--; } } class Node { Object element; Node next; Node previous; public Node(Object element,Node next,Node previous){//帶仨參的構造函數 this.element=element; this.next=next; this.previous=previous; } }
package collection; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * @author SUNHAN * @Date: 2014年9月29日 * */ public class SIterator { public static void main(String[] args) { Set set=new HashSet(); set.add("aa"); set.add("bb"); set.add("cc"); Iterator iter=set.iterator(); while(iter.hasNext()){ String str=(String) iter.next(); System.err.println(str); } for(Iterator iter1=set.iterator();iter.hasNext();){ String str=(String) iter1.next(); System.err.println(str); } List list=new ArrayList(); list.add("xxx"); list.add("yyy"); list.add("zzz"); for(Object o:list){ System.err.println(o.toString()); } } }
package collection; import java.util.HashSet; import java.util.LinkedList; import java.util.ListIterator; import java.util.Set; /** * @author SUNHAN * @Date: 2014年9月29日 * @param <K> * @param <V> */ @SuppressWarnings("unchecked") public class SimpleHashMap<K, V> { private static final int ARRAY_SiZE = 997; private LinkedList<MapEntry<K, V>>[] buckets = new LinkedList[ARRAY_SiZE]; public V put(K key, V value) { //添加一個鍵值對 V oldValue = null; int index = Math.abs(key.hashCode()) % ARRAY_SiZE; //通過哈希碼取絕對值再取模操作得到key的索引值 if(buckets[index] == null) { buckets[index] = new LinkedList<MapEntry<K, V>>(); } LinkedList bucket = buckets[index]; MapEntry newEntry = new MapEntry<K, V>(key, value); ListIterator<MapEntry<K, V>> itr = bucket.listIterator(); while(itr.hasNext()) { //遍歷,是否key已存在 MapEntry<K, V> entry = itr.next(); if(entry.getKey().equals(key)) { //存在 oldValue = entry.getValue(); itr.set(newEntry); //將新值覆蓋舊值 return oldValue; } } bucket.add(newEntry);//添加新鍵值對 return oldValue; } public V get(Object key) { //通過key得到value int index = Math.abs(key.hashCode()) % ARRAY_SiZE; //通過哈希碼取絕對值再取模操作得到key的索引值 if(buckets[index] == null) { return null; } for(MapEntry<K ,V> entry : buckets[index]) { if(entry.getKey().equals(key)) { return entry.getValue(); } } return null; } public Set<MapEntry<K, V>> entrySet() { //返回一個set Set<MapEntry<K, V>> set = new HashSet<MapEntry<K, V>>(); for(LinkedList<MapEntry<K, V>> bucket : buckets) { //遍歷數組以及LinkedList,將所有存在的鍵值對放進set中返回 if(bucket == null) continue; for(MapEntry<K, V> entry : bucket) { set.add(entry); } } return set; } public V remove(Object key) { //移除指定的鍵值對,並返回value V oldValue = null; int index = Math.abs(key.hashCode()) % ARRAY_SiZE; if(buckets[index] == null) { return null; } for(MapEntry<K, V> entry : buckets[index]) { if(entry.getKey().equals(key)) { oldValue = entry.getValue(); buckets[index].remove(entry); return oldValue; } } return oldValue; } public void clear() { //清除整個map for(int i = 0; i < buckets.length; i++) { if(buckets[i] != null) { buckets[i] = null; } } } static class MapEntry<K, V>{ K key; V value; public MapEntry(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V old = this.value; this.value = value; return old; } @Override public int hashCode() { return key == null ? 0 : key.hashCode() ^ (value == null ? 0 : value.hashCode()); } @Override public boolean equals(Object o) { if (!(o instanceof MapEntry)) { return false; } MapEntry<K, V> me = (MapEntry<K, V>) o; return (key == null ? me.getKey() == null : key.equals(me.getKey())) && (value == null ? me.getValue() == null : value.equals(me .getValue())); } @Override public String toString() { return key + "=" + value; } } }
package collection; import java.util.HashMap; public class SHashSet { HashMap map; private static final Object PRERSENT=new Object(); int size; public int size(){ return map.size(); } public SHashSet(){ map=new HashMap(); } public void add(Object o){ map.put(0, PRERSENT); } public static void main(String[] args) { } }
http://www.cnblogs.com/Eddyer/p/6025356.html