Java底層基于鏈表實現(xiàn)集合和映射--集合Set操作詳解
本文實例講述了Java底層基于鏈表實現(xiàn)集合和映射--集合Set操作。分享給大家供大家參考,具體如下:
在Java底層基于二叉搜索樹實現(xiàn)集合和映射中我們實現(xiàn)了底層基于二叉搜索樹的集合,本節(jié)就底層如何基于鏈表實現(xiàn)進行學習,注意:此處的鏈表是之前自己封裝的.
1、集合set相關(guān)功能用于鏈表本身沒有去重的效果,因此我們在做基于鏈表的集合時,需要對add()方法做一下特殊處理,如下增加一個判斷即可。
@Override public void add(E e) { if (!list.contains(e)) { list.addFirst(e); } }2.集合實現(xiàn)2.1 Set接口定義
/** * 集合的接口 */public interface Set<E> { void add(E e);//添加 <——<不能添加重復元素 void remove(E e);//移除 int getSize();//獲取大小 boolean isEmpty();//是否為空 boolean contains(E e);//是否包含元素 }3.2 基于鏈表實現(xiàn)集合Set
public class LinkedListSet<E> implements Set<E> { private LinkedList<E> list; public LinkedListSet() { list = new LinkedList<E>(); } @Override public int getSize() { return list.getSize(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public boolean contains(E e) { return list.contains(e); } @Override public void add(E e) { if (!list.contains(e)) { list.addFirst(e); } } @Override public void remove(E e) { list.removeElement(e); }}3.3測試:兩本名著的詞匯量 和不重復的詞匯量
import java.util.ArrayList;public class LinkedListSetTestDemo { public static void main(String[] args) { System.out.println('Pride and Prejudice'); //新建一個ArrayList存放單詞 ArrayList<String> words1 = new ArrayList<>(); //通過這個方法將書中所以單詞存入word1中 FileOperation.readFile('pride-and-prejudice.txt', words1); System.out.println('Total words : ' + words1.size()); LinkedListSet<String> set1 = new LinkedListSet<>(); //增強for循環(huán),定一個字符串word去遍歷words //底層的話會把ArrayList words1中的值一個一個的賦值給word for (String word : words1) set1.add(word);//不添加重復元素 System.out.println('Total different words : ' + set1.getSize()); System.out.println('-------------------'); System.out.println('Pride and Prejudice'); //新建一個ArrayList存放單詞 ArrayList<String> words2 = new ArrayList<>(); //通過這個方法將書中所以單詞存入word1中 FileOperation.readFile('a-tale-of-two-cities.txt', words2); System.out.println('Total words : ' + words2.size()); LinkedListSet<String> set2 = new LinkedListSet<>(); //增強for循環(huán),定一個字符串word去遍歷words //底層的話會把ArrayList words1中的值一個一個的賦值給word for (String word : words2) set2.add(word);//不添加重復元素 System.out.println('Total different words : ' + set2.getSize()); }}
結(jié)果:
這里需要說明一下就是關(guān)于我們統(tǒng)計的單詞數(shù)只考慮了每個單詞組成的不用,并沒有對單詞的特殊形式做區(qū)分。
在下一下節(jié),將對本節(jié)相關(guān)的進行分析【基于二分搜索樹、鏈表的實現(xiàn)的集合Set復雜度分析】
源碼地址 https://github.com/FelixBin/dataStructure/tree/master/src/SetPart
更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關(guān)文章:
1. Intellij IDEA 2019 最新亂碼問題及解決必殺技(必看篇)2. JS繪圖Flot如何實現(xiàn)動態(tài)可刷新曲線圖3. Android Manifest中meta-data擴展元素數(shù)據(jù)的配置與獲取方式4. Android自定義View實現(xiàn)掃描效果5. CSS3實現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效6. 關(guān)于HTML5的img標簽7. 未來的J2EE主流應用框架:對比Spring和EJB38. JS+css3實現(xiàn)幻燈片輪播圖9. css3溢出隱藏的方法10. ASP.NET MVC獲取多級類別組合下的產(chǎn)品
