您的位置:首页 > 其它

Commons-Collections 集合工具类的使用

2016-11-03 09:37 411 查看
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) {

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: