学习源码系列---Collection
学习源码系列---Collection
官方文档阐述
** The root interface in the <i>collection hierarchy</i>. A collection
* represents a group of objects, known as its <i>elements</i>. Some
* collections allow duplicate elements and others do not. Some are ordered
* and others unordered. The JDK does not provide any <i>direct</i>
* implementations of this interface: it provides implementations of more
* specific subinterfaces like <tt>Set</tt> and <tt>List</tt>. This interface
* is typically used to pass collections around and manipulate them where
* maximum generality is desired.
译文
集合层次结构中的根接口。一个集合表示一组对象,称为其元素。有些集合允许重复元素,有些则不允许。有些是有序的,有些是无序的。JDK没有提供这个接口的任何直接实现:它提供了更具体的子接口的实现,比如Set和List。这个接口通常用于在需要最大通用性的地方传递集合并操作它们个人理解:
父类
public interface Collection<E> extends Iterable<E> {}
继承Iterable,那么同样也同样具有了Iterable里面的相关方法。
主要方法
/**
* Returns the number of elements in this collection. If this collection
* contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
* @return the number of elements in this collection
*/
int size()
译文:返回此集合中的元素数量。如果此集合包含多个整数。MAX_VALUE元素,返回Integer.MAX_VALUE;
代码实现
public static void main(String[] args) {
Collection c=new ArrayList();
c.add("aaa");
c.add("bbb");
c.add("ccc");
System.out.println(c.size());
}
/**
* Returns <tt>true</tt> if this collection contains no elements.
*
* @return <tt>true</tt> if this collection contains no elements
*/
boolean isEmpty();
译文:如果集合内不包含任何元素,这返回true;
代码实现
public static void main(String[] args) {
Collection c=new ArrayList();
c.add("aaa");
c.add("bbb");
c.add("ccc");
System.out.println(c.isEmpty());
}
/**
* Returns <tt>true</tt> if this collection contains the specified element.
* More formally, returns <tt>true</tt> if and only if this collection
* contains at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.//这一段特别有意思
==和equals特别提醒
*/
boolean contains(Object o);
译文:如果集合包含指定的元素,则返回true。更正式地说,当且仅当这个集合返回true,包含至少一个元素。
代码实现
public static void main(String[] args) {
Collection c=new ArrayList();
c.add("aaa");
c.add("bbb");
c.add("ccc");
System.out.println(c.contains("bbb"));
}
/**
* Returns an iterator over the elements in this collection. There are no
* guarantees concerning the order in which the elements are returned
* (unless this collection is an instance of some class that provides a
* guarantee).
*
* @return an <tt>Iterator</tt> over the elements in this collection
*/
Iterator<E> iterator();
译文:返回此集合中元素的迭代器。对于返回元素的顺序没有保证(除非此集合是提供保证的某个类的实例)
代码实现
public static void main(String[] args) {
Collection c=new ArrayList();
c.add("aaa");
c.add("bbb");
c.add("ccc");
System.out.println("----------------");
Iterator iterator = c.iterator();
while(iterator.hasNext()){
Object next = iterator.next();
System.out.println(next);
}
}
/**
* Returns an array containing all of the elements in this collection.
* If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements in
* the same order.
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this collection. (In other words, this method must
* allocate a new array even if this collection is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this collection
*/
Object[] toArray();
个人译文:首先这个api是充当数组和集合之间的桥梁,其次返回包含此集合中所有元素的数组,最后返回的数组是安全的,因为我们是对集合进行操作,而没对新的数组进行操作
代码实现
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("aaa");
c.add("bbb");
c.add("ccc");
System.out.println("----------------");
Object[] objects = c.toArray();
//方法一
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i]);
}
//方法二
for (Object str:objects) {
System.out.println(str);
}
}
/**
* Returns an array containing all of the elements in this collection;
* the runtime type of the returned array is that of the specified array.
* If the collection fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of the
* specified array and the size of this collection.
*
* String[] y = x.toArray(new String[0]);
*
*/
<T> T[] toArray(T[] a);
个人译文:返回包含此集合中所有元素的数组,返回的数组指定了类型,指定了数组和集合大小
代码实现
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("aaa");
c.add("bbb");
c.add("ccc");
System.out.println("----------------");
String[] y = (String[]) c.toArray(new String[10]);
System.out.println(Arrays.toString(y));
for (int i = 0; i <y.length ; i++) {
System.out.println(y[i]);
}
}
/**
* Ensures that this collection contains the specified element (optional
* operation). Returns <tt>true</tt> if this collection changed as a
* result of the call. (Returns <tt>false</tt> if this collection does
* not permit duplicates and already contains the specified element.)<p>
*
* Collections that support this operation may place limitations on what
* elements may be added to this collection. In particular, some
* collections will refuse to add <tt>null</tt> elements, and others will
* impose restrictions on the type of elements that may be added.
* Collection classes should clearly specify in their documentation any
* restrictions on what elements may be added.<p>
*
* If a collection refuses to add a particular element for any reason
* other than that it already contains the element, it <i>must</i> throw
* an exception (rather than returning <tt>false</tt>). This preserves
* the invariant that a collection always contains the specified element
* after this call returns.
boolean add(E e);
个人译文:不能添加重复元素、不能添加null,同样也可以对添加的元素进行限制、如果出现异常,必须抛出相应的提是
/**
* Removes a single instance of the specified element from this
* collection, if it is present (optional operation). More formally,
* removes an element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>, if
* this collection contains one or more such elements. Returns
* <tt>true</tt> if this collection contained the specified element (or
* equivalently, if this collection changed as a result of the call).
*/
boolean remove(Object o);
个人译文:删除指定元素,使得该元素为null
/**
* Returns <tt>true</tt> if this collection contains all of the elements
* in the specified collection.
*/
boolean containsAll(Collection<?> c);
个人译文:如果和包含指定的集合的所有元素,则返回true
/**
* Adds all of the elements in the specified collection to this collection
* (optional operation). The behavior of this operation is undefined if
* the specified collection is modified while the operation is in progress.
* (This implies that the behavior of this call is undefined if the
* specified collection is this collection, and this collection is
* nonempty.)
*/
boolean addAll(Collection<? extends E> c);
译文:将指定集合中的所有元素添加到此集合(可选操作)。如果在操作进行期间修改了指定的集合,则此操作的行为未定义。(这意味着,如果指定的集合是这个集合,并且这个集合不是空的,则此调用的行为是未定义的。)//晦涩难懂,感觉就像,如果源对象或者目标的对象出现问题,则最后的结果不可控
/**
* Removes all of this collection's elements that are also contained in the
* specified collection (optional operation). After this call returns,
* this collection will contain no elements in common with the specified
* collection.
*/
boolean removeAll(Collection<?> c);
译文:删除指定集合中也包含的此集合的所有元素(可选操作)。此调用返回后,此集合将不包含与指定集合相同的元素。
/**
* Removes all of the elements of this collection that satisfy the given
* predicate. Errors or runtime exceptions thrown during iteration or by
* the predicate are relayed to the caller.
*/
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
译文:移除此集合中满足给定谓词的所有元素。迭代期间或谓词抛出的错误或运行时异常将传递给调用者。
[https://blog.csdn.net/qq_33829547/article/details/80277956]: Java集合中removeIf的使用
/**
* Retains only the elements in this collection that are contained in the
* specified collection (optional operation). In other words, removes from
* this collection all of its elements that are not contained in the
* specified collection.
*
* @param c collection containing elements to be retained in this collection
* @return <tt>true</tt> if this collection changed as a result of the call
* @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
* is not supported by this collection
* @throws ClassCastException if the types of one or more elements
* in this collection are incompatible with the specified
* collection
* (<a href="#optional-restrictions">optional</a>)
* @throws NullPointerException if this collection contains one or more
* null elements and the specified collection does not permit null
* elements
* (<a href="#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean retainAll(Collection<?> c);
译文:仅保留此集合中包含在指定集合中的元素(可选操作)。换句话说,从这个集合中删除指定集合中不包含的所有元素。取交集,但是这个api的功能更远不止如此。
public static void main(String args[])
{
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
list1.add("g");
list1.add("s");
list1.add("a");
list1.add("f");
list2.add("g");
list2.add("c");
list2.add("b");
list2.add("a");
list1.retainAll(list2);
System.out.print(list1);
}
/**
* Removes all of the elements from this collection (optional operation).
* The collection will be empty after this method returns.
*/
void clear();
个人译文:移除这个集合中的所有元素,这个方法返回之后,这个方法之后,这个集合将会是空的。
/**
* Compares the specified object with this collection for equality. <p>
*
* While the <tt>Collection</tt> interface adds no stipulations to the
* general contract for the <tt>Object.equals</tt>, programmers who
* implement the <tt>Collection</tt> interface "directly" (in other words,
* create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt>
* or a <tt>List</tt>) must exercise care if they choose to override the
* <tt>Object.equals</tt>. It is not necessary to do so, and the simplest
* course of action is to rely on <tt>Object</tt>'s implementation, but
* the implementor may wish to implement a "value comparison" in place of
* the default "reference comparison." (The <tt>List</tt> and
* <tt>Set</tt> interfaces mandate such value comparisons.)<p>
*
* The general contract for the <tt>Object.equals</tt> method states that
* equals must be symmetric (in other words, <tt>a.equals(b)</tt> if and
* only if <tt>b.equals(a)</tt>). The contracts for <tt>List.equals</tt>
* and <tt>Set.equals</tt> state that lists are only equal to other lists,
* and sets to other sets. Thus, a custom <tt>equals</tt> method for a
* collection class that implements neither the <tt>List</tt> nor
* <tt>Set</tt> interface must return <tt>false</tt> when this collection
* is compared to any list or set. (By the same logic, it is not possible
* to write a class that correctly implements both the <tt>Set</tt> and
* <tt>List</tt> interfaces.)
*/
boolean equals(Object o);
译文:将指定的对象与此集合进行相等性比较,Collection只是一个interface接口,所以这个equals()方法具体怎么实现的还要看实现接口的类;Collection接口原则上规定是默认“引用比较”,也就是在(某种情况下不是所有的情况下)底层比较地址值是否相等;同时Collection允许下游实现类以"值比较",也就是比较内容,这时候用hashcode散列值能加速这种比较过程。比如String字符串类的equals就是最典型的比较值-比较内容,2个字符串先比较散列值hashcode,如果不同,则不相等,如果hashcode相等,再逐个字符比较。最后得出2个字符串是否相等。hashcode是java自动维护的,默认就是内存地址的一个整数。
/**
* Returns the hash code value for this collection. While the
* <tt>Collection</tt> interface adds no stipulations to the general
* contract for the <tt>Object.hashCode</tt> method, programmers should
* take note that any class that overrides the <tt>Object.equals</tt>
* method must also override the <tt>Object.hashCode</tt> method in order
* to satisfy the general contract for the <tt>Object.hashCode</tt> method.
* In particular, <tt>c1.equals(c2)</tt> implies that
* <tt>c1.hashCode()==c2.hashCode()</tt>.
*
* @return the hash code value for this collection
*
* @see Object#hashCode()
* @see Object#equals(Object)
*/
int hashCode();
个人译文:获取集合的哈希码,再比较的时候需要观察任何覆盖对象的类;特别地,c1.equals(c2)意味着c1.hashCode()==c2. hashcode ()。
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, 0);
}
Spliterator是一个可分割迭代器(splitable iterator),可以和iterator顺序遍历迭代器一起看。jdk1.8发布后,对于并行处理的能力大大增强,Spliterator就是为了并行遍历元素而设计的一个迭代器,jdk1.8中的集合框架中的数据结构都默认实现了spliterator,参考连接https://blog.csdn.net/lh513828570/article/details/56673804

浙公网安备 33010602011771号