Commons Collections学习笔记(一)

简介:
public interface Bag extends Collection 
{
    int getCount(Object object);
    boolean add(Object object);
    boolean add(Object object, int nCopies);
    boolean remove(Object object);
    boolean remove(Object object, int nCopies);
    Set uniqueSet();
    int size();
    boolean containsAll(Collection coll);
    boolean removeAll(Collection coll);
    boolean retainAll(Collection coll);
    Iterator iterator();
}
复制代码
 

public interface SortedBag extends Bag
{
    public Comparator comparator();
    public Object first();
    public Object last();
}
 

复制代码
public abstract class DefaultMapBag implements Bag 
{
    private Map _map = null;//底层数据存储区
    private int _total = 0; //元素总个数
    private int _mods = 0;//修改次数
    public DefaultMapBag() {
    }
    protected DefaultMapBag(Map map) {
        setMap(map);
    }
    public boolean add(Object object) {
        return add(object, 1);
    }
    public boolean add(Object object, int nCopies) {
        _mods++;
        if (nCopies > 0) {
            int count = (nCopies + getCount(object));
            _map.put(object, new Integer(count));
            _total += nCopies;
            return (count == nCopies);
        } else {
            return false;
        }
    }
    public boolean addAll(Collection coll) {
        boolean changed = false;
        Iterator i = coll.iterator();
        while (i.hasNext()) {
            boolean added = add(i.next());
            changed = changed || added;
        }
        return changed;
    }
    public void clear() {
        _mods++;
        _map.clear();
        _total = 0;
    }
    public boolean contains(Object object) {
        return _map.containsKey(object);
    }
    public boolean containsAll(Collection coll) {
        return containsAll(new HashBag(coll));
    }
    public boolean containsAll(Bag other) {
        boolean result = true;
        Iterator i = other.uniqueSet().iterator();
        while (i.hasNext()) {
            Object current = i.next();
            boolean contains = getCount(current) >= other.getCount(current);
            result = result && contains;
        }
        return result;
    }
    public boolean equals(Object object) {
        if (object == this) {
            return true;
        }
        if (object instanceof Bag == false) {
            return false;
        }
        Bag other = (Bag) object;
        if (other.size() != size()) {
            return false;
        }
        for (Iterator it = _map.keySet().iterator(); it.hasNext();) {
            Object element = it.next();
            if (other.getCount(element) != getCount(element)) {
                return false;
            }
        }
        return true;
    }
    public int hashCode() {
        return _map.hashCode();
    }
    public boolean isEmpty() {
        return _map.isEmpty();
    }
    public Iterator iterator() {
        return new BagIterator(this, extractList().iterator());
    }
    static class BagIterator implements Iterator {
        private DefaultMapBag _parent = null;
        private Iterator _support = null;//原始迭代器
        private Object _current = null;//当前元素
        private int _mods = 0;
        public BagIterator(DefaultMapBag parent, Iterator support) {
            _parent = parent;
            _support = support;
            _current = null;
            _mods = parent.modCount();
        }
        public boolean hasNext() {
            return _support.hasNext();
        }
        public Object next() {
            if (_parent.modCount() != _mods) {
                throw new ConcurrentModificationException();
            }
            _current = _support.next();
            return _current;
        }
        public void remove() {
            if (_parent.modCount() != _mods) {
                throw new ConcurrentModificationException();
            }
            _support.remove();
            _parent.remove(_current, 1);
            _mods++;
        }
    }
    public boolean remove(Object object) {
        return remove(object, getCount(object));
    }
    public boolean remove(Object object, int nCopies) {
        _mods++;
        boolean result = false;
        int count = getCount(object);
        if (nCopies <= 0) {
            result = false;
        } else if (count > nCopies) {
            _map.put(object, new Integer(count - nCopies));
            result = true;
            _total -= nCopies;
        } else { // count > 0 && count <= i  
            // need to remove all
            result = (_map.remove(object) != null);
            _total -= count;
        }
        return result;
    }
    public boolean removeAll(Collection coll) {
        boolean result = false;
        if (coll != null) {
            Iterator i = coll.iterator();
            while (i.hasNext()) {
                boolean changed = remove(i.next(), 1);
                result = result || changed;
            }
        }
        return result;
    }
    public boolean retainAll(Collection coll) {
        return retainAll(new HashBag(coll));
    }
    public boolean retainAll(Bag other) {
        boolean result = false;
        Bag excess = new HashBag();
        Iterator i = uniqueSet().iterator();
        while (i.hasNext()) {
            Object current = i.next();
            int myCount = getCount(current);
            int otherCount = other.getCount(current);
            if (1 <= otherCount && otherCount <= myCount) {
                excess.add(current, myCount - otherCount);
            } else {
                excess.add(current, myCount);
            }
        }
        if (!excess.isEmpty()) {
            result = removeAll(excess);
        }
        return result;
    }
    public Object[] toArray() {
        return extractList().toArray();
    }
    public Object[] toArray(Object[] array) {
        return extractList().toArray(array);
    }
    public int getCount(Object object) {
        int result = 0;
        Integer count = MapUtils.getInteger(_map, object);
        if (count != null) {
            result = count.intValue();
        }
        return result;
    }
    public Set uniqueSet() {
        return UnmodifiableSet.decorate(_map.keySet());
    }
    public int size() {
        return _total;
    }
    protected int calcTotalSize() {
        _total = extractList().size();
        return _total;
    }
    protected void setMap(Map map) {
        if (map == null || map.isEmpty() == false) {
            throw new IllegalArgumentException("The map must be non-null and empty");
        }
        _map = map;
    }
    protected Map getMap() {
        return _map;
    }
    private List extractList() {
        List result = new ArrayList();
        Iterator i = uniqueSet().iterator();
        while (i.hasNext()) {
            Object current = i.next();
            for (int index = getCount(current); index > 0; index--) {
                result.add(current);
            }
        }
        return result;
    }
    private int modCount() {
        return _mods;
    }
    public String toString() {
        StringBuffer buf = new StringBuffer();
        buf.append("[");
        Iterator i = uniqueSet().iterator();
        while (i.hasNext()) {
            Object current = i.next();
            int count = getCount(current);
            buf.append(count);
            buf.append(":");
            buf.append(current);
            if (i.hasNext()) {
                buf.append(",");
            }
        }
        buf.append("]");
        return buf.toString();
    }
}
复制代码
 

复制代码
public class HashBag extends DefaultMapBag implements Bag 
{
    public HashBag() {
        super(new HashMap());
    }
    public HashBag(Collection coll) {
        this();
        addAll(coll);
    }
}
复制代码
 

复制代码
public class TreeBag extends DefaultMapBag implements SortedBag 
{
    public TreeBag() {
        super(new TreeMap());
    }
    public TreeBag(Comparator comparator) {
        super(new TreeMap(comparator));
    }
    public TreeBag(Collection coll) {
        this();
        addAll(coll);
    }
    public Object first() {
        return ((SortedMap) getMap()).firstKey();
    }
    public Object last() {
        return ((SortedMap) getMap()).lastKey();
    }
    public Comparator comparator() {
        return ((SortedMap) getMap()).comparator();
    }
}
复制代码
使用decorate模式的Bag工具类

复制代码
public class BagUtils 
{
    /**
     * An empty unmodifiable bag.
     */
    public static final Bag EMPTY_BAG = UnmodifiableBag.decorate(new HashBag());

    /**
     * An empty unmodifiable sorted bag.
     */
public static final Bag EMPTY_SORTED_BAG = UnmodifiableSortedBag.decorate(new TreeBag());

    public BagUtils() {//这里按常理不应该是public,应该是private才对,作者应该有其他地方要用到吧
    }
    public static Bag synchronizedBag(Bag bag) {
        return SynchronizedBag.decorate(bag);
    }
    public static Bag unmodifiableBag(Bag bag) {
        return UnmodifiableBag.decorate(bag);
    }
    public static Bag predicatedBag(Bag bag, Predicate predicate) {
        return PredicatedBag.decorate(bag, predicate);
    }
    public static Bag typedBag(Bag bag, Class type) {
        return TypedBag.decorate(bag, type);
    }
    public static Bag transformedBag(Bag bag, Transformer transformer) {
        return TransformedBag.decorate(bag, transformer);
    }
    public static SortedBag synchronizedSortedBag(SortedBag bag) {
        return SynchronizedSortedBag.decorate(bag);
    }
    public static SortedBag unmodifiableSortedBag(SortedBag bag) {
        return UnmodifiableSortedBag.decorate(bag);
    }
    public static SortedBag predicatedSortedBag(SortedBag bag, Predicate predicate) {
        return PredicatedSortedBag.decorate(bag, predicate);
    }
    public static SortedBag typedSortedBag(SortedBag bag, Class type) {
        return TypedSortedBag.decorate(bag, type);
    }
    public static SortedBag transformedSortedBag(SortedBag bag, Transformer transformer) {
        return TransformedSortedBag.decorate(bag, transformer);
    }
}
复制代码


本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2008/12/16/1356303.html,如需转载请自行联系原作者
目录
相关文章
|
6天前
|
存储 关系型数据库 分布式数据库
PostgreSQL 18 发布,快来 PolarDB 尝鲜!
PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
|
16天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1317 7
|
4天前
|
存储 人工智能 Java
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
本文讲解 Prompt 基本概念与 10 个优化技巧,结合学术分析 AI 应用的需求分析、设计方案,介绍 Spring AI 中 ChatClient 及 Advisors 的使用。
284 128
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
|
3天前
|
监控 JavaScript Java
基于大模型技术的反欺诈知识问答系统
随着互联网与金融科技发展,网络欺诈频发,构建高效反欺诈平台成为迫切需求。本文基于Java、Vue.js、Spring Boot与MySQL技术,设计实现集欺诈识别、宣传教育、用户互动于一体的反欺诈系统,提升公众防范意识,助力企业合规与用户权益保护。
|
15天前
|
机器学习/深度学习 人工智能 前端开发
通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
1375 87
|
3天前
|
JavaScript Java 大数据
基于JavaWeb的销售管理系统设计系统
本系统基于Java、MySQL、Spring Boot与Vue.js技术,构建高效、可扩展的销售管理平台,实现客户、订单、数据可视化等全流程自动化管理,提升企业运营效率与决策能力。
|
4天前
|
人工智能 Java API
AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
本文介绍AI大模型的核心概念、分类及开发者学习路径,重点讲解如何选择与接入大模型。项目基于Spring Boot,使用阿里云灵积模型(Qwen-Plus),对比SDK、HTTP、Spring AI和LangChain4j四种接入方式,助力开发者高效构建AI应用。
259 122
AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
|
5天前
|
弹性计算 安全 数据安全/隐私保护
2025年阿里云域名备案流程(新手图文详细流程)
本文图文详解阿里云账号注册、服务器租赁、域名购买及备案全流程,涵盖企业实名认证、信息模板创建、域名备案提交与管局审核等关键步骤,助您快速完成网站上线前的准备工作。
217 82
2025年阿里云域名备案流程(新手图文详细流程)