Commons-Collections 集合工具類的使用
阿新 • • 發佈:2018-12-30
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 斷言
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", "[email protected]");
map.put("sxt", "[email protected]");
//遍歷檢視
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", "[email protected]");
map.put("sxt", "[email protected]");
//反轉
System.out.println(map.inverseBidiMap().get("[email protected]"));
//遍歷檢視
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,將所有存在的