220-224 集合体系结构

220 集合体系结构

【集合知识回顾】

集合类的特点;提供一种存储空间可变的存储模型,存储的数据容量可以随时发生改变

【集合类体系结构】

先学习接口,然后学实现类

221 Collection集合概述和使用

【collection集合概述】

- 是单列集合的顶层接口,它表示一组对象,这些对象也被称为collection的元素

- JDK不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现

Collection是一个接口,不是类

【创建Collection集合的对象】

- 多态的方式

- 具体的实现类ArrayList

package e221;

//创建集合对象,涉及:向上转型,,,慢点写等系统提供联想、自动导包

//往集合添加数据,涉及:Boolean add方法,boolean add(E e),,,注意添加String类型的

--------------------------------------------------------------

(module)myCollection

(package)e221

class)CollectionDemo

--------------------------------------------------------------

import java.util.ArrayList;

import java.util.Collection;

public class CollectionDemo221 {

    public static void main(String[] args) {

        Collection<String> c = new ArrayList<String>();//左边是接口,右边是子类,这是向上转型

        c.add("221");

        c.add("hello");

        c.add("world");

        System.out.println("c:\n"+c);

//        OUTPUT:

//        c:

//[221, hello, world]

    }

}

--------------------------------------------------------------

> 来自帮助文档:

<E>是泛型,表示集合的类型

【泛型】

泛型程序设计(generic programming)是程序设计语言的一种风格或范式。泛型允许程序员在强类型程序设计语言中编写代码时使用一些以后才指定的类型,在实例化时作为参数指明这些类型。各种程序设计语言和其编译器、运行环境对泛型的支持均不一样。Ada、Delphi、Eiffel、Java、C#、F#、Swift 和 Visual Basic .NET 称之为泛型(generics);ML、Scala 和 Haskell 称之为参数多态(parametric polymorphism);C++ 和 D称之为模板。具有广泛影响的1994年版的《Design Patterns》一书称之为参数化类型(parameterized type)。

Module java.base

Package java.util

Interface Collection<E>

Type Parameters:

E - the type of elements in this collection

All Superinterfaces:

Iterable<E>

All Known Subinterfaces:

BeanContext, BeanContextServices, BlockingDeque<E>, BlockingQueue<E>, Deque<E>, EventSet, List<E>, NavigableSet<E>, Queue<E>, Set<E>, SortedSet<E>, TransferQueue<E>

All Known Implementing classes:

AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, ArrayList, AttributeList, BeanContextServicesSupport, BeanContextSupport, ConcurrentHashMap.KeySetView, ConcurrentLinkedDeque, ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet, LinkedList, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, Stack, SynchronousQueue, TreeSet, Vector

模块java.base

包java.util

接口集合<E>

类型参数:

E-此集合中元素的类型

所有超级界面:

Iterable<E>

所有已知子接口:

BeanContext、BeanContextServices、BlockingDeque<E>、BlockingQueue<E>、Deque<E>、EventSet、List<E>、NavigableSet<E>、Queue<E>、Set<E>、SortedSet<E>、TransferQueue<E>

所有已知的实现类:

AbstractCollection、AbstractList、AbstractQueue、AbstractSequentialList、AbstractSet、ArrayBlockingQueue、ArrayQueue、ArrayQuest、AttributeList、BeanContextServicesSupport、BeanContextSupport、ConcurrentHashMap.KeySetView、ConcurrentLinkedQueue、ConcurrentSkiplitSet、CopyOnWriteArrayList、CopyOnWriteArraySet、DelayQueue、,枚举集、哈希集、JobStateReasons、LinkedBlockingDeque、LinkedBlockingQueue、LinkedHashSet、LinkedList、LinkedTransferQueue、优先级BlockingQueue、优先级队列、角色列表、RoleUnresolvedList、堆栈、同步队列、树集、向量

-

The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

集合层次结构中的根接口。集合表示一组对象,称为其元素。某些集合允许重复元素,而其他集合则不允许。有些是有序的,有些是无序的。JDK不提供此接口的任何直接实现它提供更具体的子接口(如Set和List)的实现。此接口通常用于传递集合,并在需要最大通用性的地方对其进行操作。

Bags or multisets (unordered collections that may contain duplicate elements) should implement this interface directly.

包或多集(可能包含重复元素的无序集合)应直接实现此接口。

All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument. In effect, the latter constructor allows the user to copy any collection, producing an equivalent collection of the desired implementation type. There is no way to enforce this convention (as interfaces cannot contain constructors) but all of the general-purpose Collection implementations in the Java platform libraries comply.

所有通用集合实现类(通常通过其子接口之一间接实现集合)都应提供两个“标准”构造函数:一个创建空集合的void(无参数)构造函数和一个具有Collection类型的单个参数的构造函数,它创建一个新集合,该集合的元素与其参数相同。实际上,后一个构造函数允许用户复制任何集合,从而生成所需实现类型的等效集合。无法强制执行此约定(因为接口不能包含构造函数),但Java平台库中的所有通用集合实现都符合此约定。

Certain methods are specified to be optional. If a collection implementation doesn't implement a particular operation, it should define the corresponding method to throw UnsupportedOperationException. Such methods are marked "optional operation" in method specifications of the collections interfaces.

某些方法被指定为可选。如果集合实现没有实现特定的操作,它应该定义相应的方法来抛出UnsupportedOperationException。这些方法在集合接口的方法规范中标记为“可选操作”。

Some collection implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or classCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the collection may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

某些集合实现对它们可能包含的元素有限制。例如,有些实现禁止空元素,有些实现对其元素的类型有限制。尝试添加不合格的元素会引发未经检查的异常,通常为NullPointerException或classCastException。试图查询不合格元素的存在可能会引发异常,或者只返回false;有些实现将展示前一种行为,有些实现将展示后一种行为。更一般地说,在不合格元素上尝试操作(其完成不会导致将不合格元素插入到集合中)可能会引发异常,或者可能会成功(由实现选择)。此类异常在该接口规范中标记为“可选”。

It is up to each collection to determine its own synchronization policy. In the absence of a stronger guarantee by the implementation, undefined behavior may result from the invocation of any method on a collection that is being mutated by another thread; this includes direct invocations, passing the collection to a method that might perform invocations, and using an existing iterator to examine the collection.

由每个集合决定其自己的同步策略。在实现没有更强有力的保证的情况下,未定义的行为可能是由于调用另一个线程正在变异的集合上的任何方法而导致的;这包括直接调用、将集合传递给可能执行调用的方法以及使用现有迭代器检查集合。

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the contains(Object o) method says: "returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e))." This specification should not be construed to imply that invoking Collection.contains with a non-null argument o will cause o.equals(e) to be invoked for any element e. Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two elements. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.

集合框架接口中的许多方法都是根据equals方法定义的。例如,contains(Object o)方法的规范说明:“当且仅当此集合至少包含一个元素e,并且(o==null?e==null:o.equals(e)),则返回true。”此规范不应解释为暗示使用非null参数o调用collection.contains将导致o.equals(e)为任何元素e调用。实现可以自由地实现优化,从而避免equals调用,例如,首先比较两个元素的哈希代码。(Object.hashCode()规范保证两个哈希代码不相等的对象不能相等。)更一般地说,各种集合框架接口的实现可以在实现者认为合适的地方自由利用底层对象方法的指定行为。

Some collection operations which perform recursive traversal of the collection may fail with an exception for self-referential instances where the collection directly or indirectly contains itself. This includes the clone(), equals(), hashCode() and toString() methods. Implementations may optionally handle the self-referential scenario, however most current implementations do not do so.

执行递归遍历集合的某些集合操作可能会失败,但对于集合直接或间接包含自身的自引用实例,则会出现例外。这包括clone()、equals()、hashCode()和toString()方法。实现可以选择性地处理自引用场景,但是大多数当前实现不这样做。

222 Collection集合常用方法

方法名

说明

1

boolean add(E e)

添加元素

2

boolean remove(Object o)

从集合中移除指定的元素

3

coid clear()

清空集合中的元素

4

boolean contains(Object o)

判断集合中是否存在指定的元素

5

boolean isEmpty()

判断集合是否为空

6

int size()

集合的长度,也就是集合中元素的个数

灰色底纹表示不需要手动输入,系统自动标记

--------------------------------------------------------------

package e221asn;

//思路

//创建集合对象

//测试常用方法1:boolean add(E e) 添加元素

//alt 7打开窗口,可查看类的源码

//boolean remove(Object o) 从集合中移除指定的元素

//coid clear() 清空集合中的元素

//boolean contains(Object o) 判断集合中是否存在指定的元素

//boolean isEmpty() 判断集合是否为空

//int size() 集合的长度,也就是集合中元素的个数

//灰色底纹表示不需要手动输入,系统自动标记

import java.util.ArrayList;

import java.util.Collection;

public class CollectionDemo222 {

    public static void main(String[] args) {

        Collection<String> c = new ArrayList<String>();

//        add

        System.out.println("c.add():");

        System.out.println(c.add("222"));//c.add()放在sout里就添加元素并显示true,单独一行就默默添加元素

        System.out.println(c.add("hello"));

        c.add("hello");//ArrayList可添加重复元素

        c.add("world");

        System.out.println("c:\n\t"+c);

//        remove

        c.remove("hello");

        System.out.println("after remove:\n\t"+c);

//        clear

        c.clear();

        System.out.println("after clear:\n\t"+c);

//        contain

        System.out.println("c.contain():\n\t"+c.contains("hello"));

//        isEmpty

        System.out.println("isEmpty:\n\t"+c.isEmpty());

//        size

        System.out.println("size:\n\t"+c.size());

    }

}

--------------------------------------------------------------

c.add():

true

true

c:

[222, hello, hello, world]

after remove:

[222, hello, world]

after clear:

[]

c.contain():

false

isEmpty:

true

size:

0

> rename

如何重命名包?refacter->rename

223 Collection集合的遍历

Iterator:迭代器,集合的专用遍历方式

- Iterator<E> iterator(),返回此集合中元素的迭代器,通过集合的iterator()方法得到

- Iterator迭代器是通过iterator()方法得到的,所以说Iterator依赖于集合而存在

> Iterator是一个接口,iterator()是Collection类的方法

【Iterator中的常用方法】

(帮助文档)

Module java.base,Package java.util,Interface Iterator<E>

方法

描述

forEachRemaining(Consumer<? superE> action)

对每个剩余元素执行给定的操作,直到所有元素都被处理或动作引发异常

hasNext()

(判断)如果迭代具有更多元素,则返回true

next()

(返回)返回迭代中的下一个元素

remove()

从底层集合中删除此迭代器返回的最后一个元素

(module)myCollection

(package)e223

class)CollectionDemo

--------------------------------------------------------------

package e223;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

//      思路

//      创建集合,添加元素

//      遍历集合:

//      1.得到集合的迭代器,怎么做?——写c.iterator(),按ctrl alt v

//      2.刚刚创建的东西,返回什么?——查看源码找答案,ctrl b方法名‘iterator’,idea打开了Collection类源码,

//      但我们需要找iterator具体实现的源码,因此我们ctrl b打开ArrayList的源码

//      打开ArrayList的源码后,找iterator方法:

//      public Iterator<E> iterator() {

//        return new Itr();

//      }

//      接着找Itr:

//      private class Itr implements Iterator<E> {...}

//      Itr是个内部类,总结,源码通过多态的方式得到iterator的对象

//      3.使用next方法获取元素

//      4.综合使用next方法、hasNext方法、while-loop,实现一套代码遍历整个集合且不复制不越界的目标

public class IteratorDemo {

    public static void main(String[] args) {

        Collection<String> c = new ArrayList<String>();

        c.add("223");

        c.add("iterator");

        c.add("hello");

//      1.

        Iterator<String> it = c.iterator();

//      3.

        System.out.println("it.next():\n\t"+it.next());

        System.out.println("it.next():\n\t"+it.next());

        System.out.println("it.next():\n\t"+it.next());

        System.out.println("一共3个元素,第4次使用next会怎样?\n\t"+it.next());

        //报错了:

        // NoSuchElementException

//        被各种访问器方法抛出,表示被请求的元素不存在

//        4.

        while(it.hasNext() == true){

//            System.out.println(it.next());

            String s = it.next();

            System.out.println(s);

//            直接写屏获取到的内容,不如把内容赋值给一个变量然后输出

//            这是因为实际工作中,获取到的内容可能不为写屏,为其他目的

        }

    }

}

224 集合使用步骤图解

内存使用过程图解

【思路】

1.创建集合对象

2.添加元素。。。创建元素,添加元素到集合。

3.遍历集合。。。通过集合对象获取迭代器对象,通过迭代器对象的hasNext方法判断是否还有元素,通过迭代器对象的next方法获取下一个元素,通过while循环实现对整个集合的遍历

Guess you like

Origin blog.csdn.net/m0_63673788/article/details/121487478