public interface Collection<E> extends Iterable<E> {}
Collection接口:泛型接口,继承Iterable泛型接口,暂不声明类型,等到子类或者创建对象时再传递类型参数。
泛型:参数化类型。
Collection接口有自己定义的抽象方法,还有继承自Iterable的抽象方法和默认方法(JDK 1.8新特性)。
public interface Iterable<T> {
Iterator<T> iterator();
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
}
Iterable接口的默认方法forEach,用于遍历集合,参数是一个Consumer接口子类对象。由于Consumer接口是一个函数式接口,所以可以传递Lambda表达式参数。
抽象方法iterator,返回一个迭代器对象Iterator,用于遍历集合。ArrayList的实现是返回一个Itr的内部类对象。这个Itr内部类实现Iterator接口。
方法名 | 描述 |
---|---|
boolean add(Object e) | 向集合中添加一个元素 |
boolean addAll(Collection<? extend E> coll) | 取两个集合的并集赋值给当前集合 |
default void forEach(Consumer<? super T> action) | 遍历集合,打印输出,底层为增强for |
int size() | 返回此集合的元素数 |
boolean isEmpty() | 判断集合是否包含元素,底层判断size == 0 |
void clear() | 删除集合中所有元素 |
package org.westos.demo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
/**
* @author lwj
* @date 2020/5/12 11:07
*/
public class MyTest {
public static void main(String[] args) {
Collection coll = new ArrayList();
//多态,只能调用Collection接口中的方法,执行ArrayList中实现后的方法
coll.add("AA");
//coll.add(Object e)
coll.add("BB");
coll.add(123);
//123自动装箱,Integer.valueOf(123)
coll.add(new Date());
coll.forEach(System.out::println);
//forEach方法,继承自Iterable接口的默认方法(接口在JDK1.8中可以有默认方法和静态方法)
//AA
//BB
//123
//Tue May 12 11:16:47 CST 2020
System.out.println(coll.size());
//4
//coll.size() 获取集合的长度
Collection coll2 = new ArrayList();
coll2.add(456);
coll2.add("CC");
coll.addAll(coll2);
coll.forEach(System.out::println);
//AA
//BB
//123
//Tue May 12 11:24:14 CST 2020
//456
//CC
System.out.println(coll.size());
//6
System.out.println(coll);
//[AA, BB, 123, Tue May 12 11:24:56 CST 2020, 456, CC]
//ArrayList的toString()方法:ArrayList的父类已经重写了Object的toString方法,它只需要继承即可
System.out.println(coll.isEmpty());
//false
//判断集合是否有元素
System.out.println(coll2.isEmpty());
//false
coll.clear();
//清空集合
System.out.println(coll);
//[]
}
}
方法名 | 描述 |
---|---|
boolean contains(Object o) | 判断集合中是否包含此元素 |
boolean containsAll(Collection<? extends E> c) | 判断集合是否包含参数集合的所有元素 |
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
//判断一个集合中是否包含此元素,使用List接口的indexOf(o)判断此元素第一次出现的索引是否大于等于0
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
//indexOf()方法:使用此对象和集合中每一个元素进行比较,利用此对象所在类的equals()方法,即:由该类的equals()方法决定两个元素是否相等,比如String类判断字符串内容,Integer类判断intValue()是否相等,如果是自定义类型,那么如果不重写equals()方法,默认按照元素的地址值比较。
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
//Collection接口的containsAll()方法的实现在AbstractCollection抽象类中
//遍历参数集合,如果有一个不再集合中,返回false
package org.westos.demo;
import java.util.Objects;
/**
* @author lwj
* @date 2020/5/12 11:52
*/
public class Person {
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
System.out.println("Person equals...");
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(name, person.name) &&
Objects.equals(age, person.age);
}
@Override
public String toString() {
return "Person{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
‘}‘;
}
}
package org.westos.demo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
/**
* @author lwj
* @date 2020/5/12 11:36
*/
public class MyTest2 {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("张三", 20));
coll.add(new String("Tom"));
coll.add(false);
//添加自定义类型
System.out.println(coll.contains(new String("Tom")));
//使用"Tom"字符串去和集合中每个元素进行比较,使用String类的equals()方法比较字符串内容而不是Object类的地址值
//true
System.out.println(coll.contains(456));
//Integer类的equals方法比较的是对象的intValue()值
//true
System.out.println(coll.contains(new Person("张三", 20)));
//判断是否包含自定义类型,该自定义类型必须有自己的equals()逻辑
//Person equals...
//Person equals...
//Person equals...
//true
//使用contains()的参数和集合中每一个元素比较,比较到index=2的元素时返回true,所以Person类的equals()执行三次
Collection coll2 = Arrays.asList(123, 456, "Tom", new Person("张三", 20));
System.out.println(coll.containsAll(coll2));
//判断参数集合中的元素是否都存在于当前集合
//Person equals...
//Person equals...
//Person equals...
//true
}
}
方法名 | 描述 |
---|---|
boolean remove(Object o) | 移除集合中的元素 |
boolean removeAll(Collection<? extends E> c) | 取两个集合的补集赋值给当前集合 |
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//Collection集合允许存储null,如果参数不是null,那么遍历集合,使用equals()方法判断,最后使用fastRemove()方法(System.arraycopy)
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
package org.westos.demo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
/**
* @author lwj
* @date 2020/5/12 12:40
*/
public class MyTest3 {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("张三", 20));
coll.add(new String("Tom"));
coll.add(false);
boolean remove = coll.remove(123);
//返回值:是否移除成功
System.out.println(remove);
//true
System.out.println(coll);
//[456, Person{name=‘张三‘, age=20}, Tom, false]
boolean remove1 = coll.remove(new Person("张三", 20));
System.out.println(remove1);
//Person equals...
//Person equals...
//true
System.out.println(coll);
//[456, Tom, false]
//removeAll() 取集合的补集
//addAll() 取集合的并集
//retainAll() 取集合的交集
Collection coll2 = Arrays.asList(456, "Cherry");
coll.removeAll(coll2);
System.out.println(coll);
//[Tom, false]
}
}
方法名 | 描述 |
---|---|
boolean retainAll(Collection<? extends E> c) | 取两个集合的交集赋值给当前集合 |
boolean equals(Object o) |
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}
//equals()方法是比较两个集合对应索引的元素是否相等
package org.westos.demo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
/**
* @author lwj
* @date 2020/5/12 12:51
*/
public class MyTest4 {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("张三", 20));
coll.add(new String("Tom"));
coll.add(false);
Collection coll2 = Arrays.asList(123, "Cherry", new Person("张三", 20));
boolean b = coll.retainAll(coll2);
System.out.println(b);
//Person equals...
//Person equals...
//Person equals...
//true
System.out.println(coll);
//[123, Person{name=‘张三‘, age=20}]
System.out.println(coll2);
//[123, Cherry, Person{name=‘张三‘, age=20}]
Collection coll3 = Arrays.asList(new Person("张三", 20), 123);
boolean equals = coll.equals(coll3);
System.out.println(equals);
}
}
方法名 | 描述 |
---|---|
Object[] toArray() | 集合转为数组 |
//数组转集合
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
//Arrays类的一个内部类ArrayList
}
//泛型方法
package org.westos.demo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author lwj
* @date 2020/5/12 13:04
*/
public class MyTest5 {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("张三", 20));
coll.add(new String("Tom"));
coll.add(false);
Object[] objects = coll.toArray();
//集合 ---> 数组
System.out.println(Arrays.toString(objects));
//[123, 456, Person{name=‘张三‘, age=20}, Tom, false]
//数组 ---> 集合
List<Object> list = Arrays.asList(objects);
//可变参数本质上是一个数组
System.out.println(list);
//[123, 456, Person{name=‘张三‘, age=20}, Tom, false]
List<int[]> ints = Arrays.asList(new int[]{1, 2, 3});
//本意是想传入一个int类型的数组,但是,asList方法以为你想传递一个参数,int[]类型(引用类型),正确的传递int类型数组应该是
List<Integer> integers = Arrays.asList(1, 2, 3);
//自动装箱
//或者
List<Integer> integers1 = Arrays.asList(new Integer[]{1, 2, 3});
}
}
使用Iterator遍历Collection集合
方法名 | 描述 |
---|---|
Iterator iterator() | 获取遍历集合的迭代器对象 |
package org.westos.demo2;
import org.westos.demo.Person;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* @author lwj
* @date 2020/5/12 13:27
*/
public class MyTest {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("张三", 20));
coll.add(new String("Tom"));
coll.add(false);
Iterator iterator = coll.iterator();
//迭代器接口
System.out.println(iterator);
//java.util.ArrayList$Itr@1b6d3586
//ArrayList的内部类
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}
//123
//456
//Person{name=‘张三‘, age=20}
//Tom
//false
}
}
Iterator的注意事项:
package org.westos.demo2;
import org.westos.demo.Person;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* @author lwj
* @date 2020/5/12 13:36
*/
public class MyTest2 {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("张三", 20));
coll.add(new String("Tom"));
coll.add(false);
//Iterator接口的错误使用
//方式一:
Iterator iterator = coll.iterator();
while (iterator.next() != null) {
Object next = iterator.next();
System.out.println(next);
}
//456
//Tom
//Exception in thread "main" java.util.NoSuchElementException
// at java.util.ArrayList$Itr.next(ArrayList.java:862)
// at org.westos.demo2.MyTest2.main(MyTest2.java:26)
//方式二:
while (coll.iterator().hasNext()) {
Object next = coll.iterator().next();
System.out.println(next);
}
//死循环,不断的输出集合的第一个元素
}
}
Iterator的remove()方法
package org.westos.demo2;
import org.westos.demo.Person;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* @author lwj
* @date 2020/5/12 13:41
*/
public class MyTest3 {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("张三", 20));
coll.add(new String("Tom"));
coll.add(false);
Iterator iterator = coll.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
if (next.equals(123)) {
iterator.remove();
}
}
System.out.println(coll);
//Person equals...
//[456, Person{name=‘张三‘, age=20}, Tom, false]
coll.removeIf(next -> next.equals(456));
//遍历集合删除元素
//底层使用的就是迭代器Iterator的remove()方法
System.out.println(coll);
//Person equals...
//[Person{name=‘张三‘, age=20}, Tom, false]
}
}
注意事项:
1、Iterator可以删除集合的元素,但是遍历过程中通过迭代器对象的remove()方法,而不是集合对象的remove()方法;
2、如果还未调用next()或者在上一次调用next()之后已经调用了remove()方法,则不能调用remove()方法,会报异常。
JDK 1.5的新特性,用于迭代访问数组和集合。
package org.westos.demo2;
import org.westos.demo.Person;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author lwj
* @date 2020/5/12 13:53
*/
public class MyTest4 {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("张三", 20));
coll.add(new String("Tom"));
coll.add(false);
//快捷方式:coll.for 集合名.for
//增强for遍历集合底层采用Iterator迭代器
for (Object o : coll) {
System.out.println(o);
}
//123
//456
//Person{name=‘张三‘, age=20}
//Tom
//false
int[] arr = new int[]{1, 2, 3, 4, 5};
//快捷方式:arr.for 数组名.for
for (int i : arr) {
System.out.println(i);
}
//1
//2
//3
//4
//5
}
}
原文:https://www.cnblogs.com/shawnyue-08/p/12877754.html