Java 核心技术 读书笔记-集合类

Collection

The fundamental interface for collection classes in the Java library is the Collection
interface. The interface has two fundamental methods:

public interface Collection<E>
{
boolean add(E element);
Iterator<E> iterator();
. . .
}

Iterators

public interface Iterator<E>
{
E next();
boolean hasNext();
void remove();
default void forEachRemaining(Consumer<? super E> action);
}
  • 通常用hasnext()和next()方法遍历
Collection<String> c = . . .;
Iterator<String> iter = c.iterator();
while (iter.hasNext())
{
String element = iter.next();
do something with element
}
//or
for (String element : c)
{
do something with element
}
public interface Iterable<E>
{
Iterator<E> iterator();
. . .
}

As of Java SE 8, you don’t even have to write a loop. You can call the forEachRemaining
method with a lambda expression that consumes an element. The lambda
expression is invoked with each element of the iterator, until there are none left.

iterator.forEachRemaining(element -> do something with element);

与其他语言的迭代器不同,Java迭代器无法回退,原理类似下图
在这里插入图片描述

Iterator<String> it = c.iterator();
it.next(); // skip over the first element
it.remove(); // now remove it
  • remove() 会删除上个元素,如果还没开始迭代没有上个元素会报IllegalStateException错误
//实例
import java.util.*;

public interface MyQueue<E> {


    public static void main(String[] args) {
       Collection<String> c= new HashSet<>();
        for (int i = 1; i < 10; i++) {
            c.add(Integer.toString(i));
        }

        Iterator<String> it = c.iterator();
        it.next(); // skip over the first element
        it.remove(); // now remove it
        while (it.hasNext()){
            System.out.println(it.next());
            it.remove();
        }
    }
}

Generic Utility Methods

int size()
boolean isEmpty()
boolean contains(Object obj)
boolean containsAll(Collection<?> c)
boolean equals(Object other)
boolean addAll(Collection<? extends E> from)
boolean remove(Object obj)
boolean removeAll(Collection<?> c)
void clear()
boolean retainAll(Collection<?> c)
Object[] toArray()
<T> T[] toArray(T[] arrayToFill)
  • java实现了和collection接口类似的抽象类
public abstract class AbstractCollection<E>
implements Collection<E>
{
. . .
public abstract Iterator<E> iterator();
public boolean contains(Object obj)
{
for (E element : this) // calls iterator()
if (element.equals(obj))
return = true;
return false;
}
. . .
}
> 所有collection实现类都会实现的方法
java.util.Collection<E> 1.2
• Iterator<E> iterator()
returns an iterator that can be used to visit the elements in the collection.int size()
returns the number of elements currently stored in the collection.boolean isEmpty()
returns true if this collection contains no elements.boolean contains(Object obj)
returns true if this collection contains an object equal to obj .boolean containsAll(Collection<?> other)
returns true if this collection contains all elements in the other collection.boolean add(Object element)
adds an element to the collection. Returns true if the collection changed as a result
of this call.boolean addAll(Collection<? extends E> other)
adds all elements from the other collection to this collection. Returns true if the
collection changed as a result of this call.boolean remove(Object obj)
removes an object equal to obj from this collection. Returns true if a matching object
was removed.boolean removeAll(Collection<?> other)
removes from this collection all elements from the other collection. Returns true if
the collection changed as a result of this call.default boolean removeIf(Predicate<? super E> filter) 8
removes all elements for which filter returns true . Returns true if the collection
changed as a result of this call.void clear()
removes all elements from this collection.boolean retainAll(Collection<?> other)
removes all elements from this collection that do not equal one of the elements in
the other collection. Returns true if the collection changed as a result of this call.
• Object[] toArray()
returns an array of the objects in the collection.<T> T[] toArray(T[] arrayToFill)
returns an array of the objects in the collection. If arrayToFill has sufficient length,
it is filled with the elements of this collection. If there is space, a null element is ap-
pended. Otherwise, a new array with the same component type as arrayToFill and
the same length as the size of this collection is allocated and filled.

在这里插入图片描述
在这里插入图片描述

NOTE: To avoid carrying out random access operations for linked lists, Java
SE 1.4 introduced a tagging interface, RandomAccess .That interface has no methods,
but you can use it to test whether a particular collection supports efficient random
access:
if (c instanceof RandomAccess)
{
use random access algorithm
}
else
{
use sequential access algorithm
}

The Set interface is identical to the Collection interface, but the behavior of the
methods is more tightly defined. The add method of a set should reject duplicates.
The equals method of a set should be defined so that two sets are identical if they
have the same elements, but not necessarily in the same order. The hashCode method
should be defined so that two sets with the same elements yield the same
hash code.

常用集合==============================
在这里插入图片描述在这里插入图片描述

Linkedlist

Java 中的linkedlist为双向指针连接如下图
在这里插入图片描述

List<String> staff = new LinkedList<>(); // LinkedList implements List
staff.add("Amy");
staff.add("Bob");
staff.add("Carl");
Iterator iter = staff.iterator();
String first = iter.next(); // visit first element
String second = iter.next(); // visit second element
iter.remove(); // remove last visited element
  • 对与linkedlist的add()方法来说,新加入的元素会放在iter迭代器当前的上一个位置上.
  • 一个迭代器在到达一个节点时如果该节点被从list中remove会报错
List<String> list = . . .;
ListIterator<String> iter1 = list.listIterator();
ListIterator<String> iter2 = list.listIterator();
iter1.next();
iter1.remove();
iter2.next(); // throws ConcurrentModificationException
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值