`
san_yun
  • 浏览: 2638451 次
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

友好的泛型Collections

 
阅读更多
在java程序中用的最多的就是泛型容器,比如:
Map<String,String> map = new HashMap<String,String>()
通过Generi可以这样简写:

Map<String,String> map = Generi.map()
List<String> list = Generic.list("1","2","3")

其实直接使用guava比较强大---》http://bastengao.iteye.com/blog/1134887


package org.python.util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Static methods to make instances of collections with their generic types inferred from what
 * they're being assigned to. The idea is stolen from <code>Sets</code>, <code>Lists</code> and
 * <code>Maps</code> from <a href="http://code.google.com/p/google-collections/">Google
 * Collections</a>.
 */
public class Generic {

    /**
     * Our default ConcurrentHashMap sizes. Only concurreny level differs from
     * ConcurrentHashMap's defaults: it's significantly lower to reduce allocation cost.
     */
    public static final int CHM_INITIAL_CAPACITY = 16;
    public static final float CHM_LOAD_FACTOR = 0.75f;
    public static final int CHM_CONCURRENCY_LEVEL = 2;

    /**
     * Makes a List with its generic type inferred from whatever it's being assigned to.
     */
    public static <T> List<T> list() {
        return new ArrayList<T>();
    }
    /**
     * Makes a List with its generic type inferred from whatever it's being assigned to filled with
     * the items in <code>contents</code>.
     */
    public static <T, U extends T> List<T> list(U...contents) {
        List<T> l = new ArrayList<T>(contents.length);
        for (T t : contents) {
            l.add(t);
        }
        return l;
    }

    /**
     * Makes a Map using generic types inferred from whatever this is being assigned to.
     */
    public static <K, V> Map<K, V> map() {
        return new HashMap<K, V>();
    }

    /**
     * Makes a ConcurrentMap using generic types inferred from whatever this is being
     * assigned to.
     */
    public static <K, V> ConcurrentMap<K, V> concurrentMap() {
        return new ConcurrentHashMap<K, V>(CHM_INITIAL_CAPACITY, CHM_LOAD_FACTOR,
                                           CHM_CONCURRENCY_LEVEL);
    }

    /**
     * Makes a Set using the generic type inferred from whatever this is being assigned to.
     */
    public static <E> Set<E> set() {
        return new HashSet<E>();
    }

    /**
     * Makes a Set using the generic type inferred from whatever this is being assigned to filled
     * with the items in <code>contents</code>.
     */
    public static <T, U extends T> Set<T> set(U...contents) {
        Set<T> s = new HashSet<T>(contents.length);
        for (U u : contents) {
            s.add(u);
        }
        return s;
    }

    /**
     * Makes a Set, ensuring safe concurrent operations, using generic types inferred from
     * whatever this is being assigned to.
     */
    public static <E> Set<E> concurrentSet() {
        return newSetFromMap(Generic.<E, Boolean>concurrentMap());
    }

    /**
     * Return a Set backed by the specified Map with the same ordering, concurrency and
     * performance characteristics.
     *
     * The specified Map must be empty at the time this method is invoked.
     *
     * Note that this method is based on Java 6's Collections.newSetFromMap, and will be
     * removed in a future version of Jython (likely 2.6) that will rely on Java 6.
     *
     * @param map the backing Map
     * @return a Set backed by the Map
     * @throws IllegalArgumentException if Map is not empty
     */
    public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
        return new SetFromMap<E>(map);
    }

    /**
     * A Set backed by a generic Map.
     */
    private static class SetFromMap<E> extends AbstractSet<E>
        implements Serializable {

        /** The backing Map. */
        private final Map<E, Boolean> map;

        /** Backing's KeySet. */
        private transient Set<E> keySet;

        public SetFromMap(Map<E, Boolean> map) {
            if (!map.isEmpty()) {
                throw new IllegalArgumentException("Map is non-empty");
            }
            this.map = map;
            keySet = map.keySet();
        }

        @Override
        public int size() {
            return map.size();
        }

        @Override
        public boolean isEmpty() {
            return map.isEmpty();
        }

        @Override
        public boolean contains(Object o) {
            return map.containsKey(o);
        }

        @Override
        public boolean containsAll(Collection<?> c) {
            return keySet.containsAll(c);
        }

        @Override
        public Iterator<E> iterator() {
            return keySet.iterator();
        }

        @Override
        public Object[] toArray() {
            return keySet.toArray();
        }

        @Override
        public <T> T[] toArray(T[] a) {
            return keySet.toArray(a);
        }

        @Override
        public boolean add(E e) {
            return map.put(e, Boolean.TRUE) == null;
        }

        @Override
        public boolean remove(Object o) {
            return map.remove(o) != null;
        }

        @Override
        public boolean removeAll(Collection<?> c) {
            return keySet.removeAll(c);
        }

        @Override
        public boolean retainAll(Collection<?> c) {
            return keySet.retainAll(c);
        }

        @Override
        public void clear() {
            map.clear();
        }

        @Override
        public boolean equals(Object o) {
            return o == this || keySet.equals(o);
        }

        @Override
        public int hashCode() {
            return keySet.hashCode();
        }

        @Override
        public String toString() {
            return keySet.toString();
        }

        private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
            in.defaultReadObject();
            keySet = map.keySet();
        }
    }

}
分享到:
评论

相关推荐

    [Java泛型和集合].(Java.Generics.and.Collections).文字版

    本资料 "[Java泛型和集合].(Java.Generics.and.Collections).Maurice.Naftalin&amp;Philip.Wadler.文字版" 由知名专家Maurice Naftalin和Philip Wadler编著,提供了关于这些主题的深入理解。 **Java泛型** 是自Java...

    Java Generics and Collections (Java泛型与集合)

    通过阅读"Java Generics and Collections",开发者不仅可以掌握Java泛型和集合的基本使用,还能深入了解它们的高级特性和最佳实践,从而在实际项目中编写出更高质量的代码。这本书对于Java程序员来说是一份宝贵的...

    C# System.Collections 非泛型接口方法解析.pdf

    在C#编程中,System.Collections命名空间包含了许多非泛型集合接口,这些接口是.NET框架早期版本的基础,尽管现在泛型集合接口(如`IEnumerable&lt;T&gt;`)更为常用,但理解非泛型接口对于维护旧代码或处理特定场景仍然很...

    泛型集合泛型集合泛型集合

    在C#中,`System.Collections.Generic`命名空间提供了多个泛型集合类,如`List&lt;T&gt;`、`Dictionary, TValue&gt;`等,它们替代了早期的非泛型集合,如`ArrayList`和`Hashtable`,因为泛型集合能确保在编译时就检查类型匹配...

    lindexi#lindexi.github.io#dotnet 非泛型 类型 System.Collections.IEnum

    dotnet 非泛型 类型 System.Collections.IEnumerable 不能与类型实参一起使用如果在开发的时候遇到非泛型 类型“IEnumer

    C#泛型集合与非泛型集合

    非泛型集合主要位于 `System.Collections` 命名空间中,包括但不限于 `ArrayList`, `Hashtable`, `Queue`, `SortedList`, `Stack` 等。这些集合在设计之初并未考虑到类型安全性的问题,因此它们只能存储 `object` ...

    commons-collections-3.2.2-bin.zip

    8. **泛型支持**:Collections库在3.2.2版本中已经支持Java泛型,这使得代码更具类型安全性和可读性。 9. **性能优化**:对一些常见操作进行了优化,如列表的快速填充、集合的复制等,提高了代码执行效率。 在实际...

    commons-collections-3.2.2-bin.tar包

    10. **泛型支持**:尽管在Java 5引入泛型时,Commons Collections已经存在,但它通过桥接方法对泛型提供了很好的支持,允许在不支持泛型的旧代码和新代码之间平滑过渡。 总之,`commons-collections-3.2.2-bin.tar`...

    Jdk15泛型的实现

    例如,`Collections.sort(List)`就是一个泛型算法,可以对任何实现了`Comparable&lt;T&gt;`接口的列表进行排序。 #### 使用与自定义泛型 在使用泛型类或泛型算法时,理解类型参数的约束至关重要。例如,如果一个泛型类...

    泛型和泛型集合类用法

    .NET Framework 2.0引入了一系列泛型集合类,这些集合类位于`System.Collections.Generic`命名空间中。与非泛型集合相比,泛型集合提供了更强的类型安全性,减少了运行时的装箱与拆箱操作,提高了程序性能。 #### ...

    commons-beanutils、commons-collections、commons-collections等常用jar 包下载

    - 与Java 5及更高版本的兼容性:使用泛型、枚举和可变参数等特性。 - 性能优化:部分算法和实现进行了性能提升。 - 新的集合实现:例如双向映射、有序集合、多值映射等。 - 新的功能:如流API支持、更强大的函数...

    xe7结构体泛型

    例如,`System.Collections.Generic.List&lt;T&gt;`就是一个泛型结构体,其中`T`是一个类型参数,代表了列表可以存储的任意类型。我们可以通过指定具体的类型来实例化这个泛型结构体,如`List&lt;int&gt;`或`List&lt;string&gt;`。 ...

    java泛型技术之发展

    2. 泛型方法:如`Collections.sort()`方法接受一个带类型参数的列表,可以对不同类型的数据进行排序。 3. 泛型接口:如`Comparable&lt;T&gt;`接口,用于定义对象之间的比较规则。 4. 实现多态性:泛型可以用来创建多态的...

    commons-collections4-4.1.jar

    1. **泛型支持**:Commons Collections 4引入了全面的泛型支持,这意味着你可以创建类型安全的集合,避免了运行时类型转换异常。这提高了代码的稳定性和安全性。 2. **Bag接口**:在Java标准库中没有提供类似的数据...

    C_泛型集合

    创建泛型集合主要使用`System.Collections.Generic`命名空间下的`List&lt;T&gt;`类。以下是一个创建和操作`Person`对象集合的例子: ```csharp class Person { public string Name { get; } public int Age { get; } ...

    commons-collections所有版本(1.0-3.2.1).zip

    从某个版本开始,Commons Collections引入了泛型,使得代码更加类型安全,避免了不必要的类型转换,并提高了编译时的错误检查能力。 **版本兼容性** 由于这个压缩包包含了从1.0到3.2.1的所有版本,因此可以根据你的...

    Java集合框架及泛型

    6. **Collections**: 这是一个包含各种集合操作的工具类,如排序、查找、翻转等。提供的算法类包括`sort()`, `binarySearch()`, `reverse()`, `shuffle()`等。 泛型是Java中处理类型安全的一种方式,允许我们在类、...

    C# 泛型 C# 泛型

    6. **泛型集合**:C#的System.Collections.Generic命名空间提供了许多泛型集合,如List、Dictionary, TValue&gt;、Queue和Stack等。这些集合比非泛型版本更安全,因为它们在编译时就进行了类型检查,减少了运行时的错误...

    深入浅出.NET泛型编程

    .NET 2.0 中的 `System.Collections.Generic` 命名空间包含了多种泛型集合,这些集合类已经被“参数化”,即允许开发者指定特定的类型作为泛型参数。使用泛型集合非常直观,只需要在类型名称后加上尖括号 (`&lt;&gt;`),并...

Global site tag (gtag.js) - Google Analytics