java常用集合详解 contains

java集合是对常用数据集合的封装,差不多就是数组吧,验证某个元素是否在数据集合里,最原始的方法是,用个循环,"某个元素"与数据集合中的每个元素逐个进行比较.

java 对常用的一些方法进行了封装,其中就包括,验证某个元素是否在集合----contains(Object);

    是否有序 是否允许元素重复
Collection
List
Set AbstractSet
  HashSet
  TreeSet 是(用二叉排序树)
Map AbstractMap 使用key-value来映射和存储数据,key必须唯一,value可以重复
  HashMap
  TreeMap 是(用二叉排序树)

set类是有自由索引,下面是接口实现的源代码,关键在key和value,在set中,key似乎就是value.

/**
     * Returns <tt>true</tt> if this set contains the specified element.
     * More formally, returns <tt>true</tt> if and only if this set
     * contains an element <tt>e</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
     *
     * @param o element whose presence in this set is to be tested
     * @return <tt>true</tt> if this set contains the specified element
     */
    public boolean contains(Object o) {
        return map.containsKey(o);
    }
 /**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }
 /**
     * Returns the entry associated with the specified key in the
     * HashMap.  Returns null if the HashMap contains no mapping
     * for the key.
     */
    final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

至于list类源码实现方式真的最基本的循环查找,不过有这些基本封装可以让代码更整洁.

学习的时间不一定要特定安排
原文地址:https://www.cnblogs.com/zhongzheng123/p/5286237.html