一、介绍
Iterable、Collection和List都是Java里的接口

- Iterable 接口是 Java 集合框架的顶级接口,实现此接口使集合对象可以通过迭代器遍历自身元素
- Collection:
public interface Collection<E>extends Iterable<E>{}
Collection是一个接口,是高度抽象出来的集合,它包含了集合的基本操作:添加、删除、清空、遍历(读取)、是否为空、获取大小、是否保护某元素等等
- List:继承自Collection,是集合的一种,List是一个有序集合,可以存放重复元素,每个元素都有自己的索引,第一个元素的索引是0。由于继承了Collection,List也包含了Collection中的所有接口,此外,List还有自己的接口。
二、常用的方法
1.Iterable的源码
public interface Iterable<T> {
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
Iterator<T> iterator();
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
}
其中提供了一个 iterator() 方法,这个方法返回一个 Iterator 对象:用来迭代的对象(被称为迭代器),就可以说这个对象具备迭代能力。
2.Collection
常见的方法有:
1.添加
boolean add(Object obj); --添加
boolean addAll(Collection coll) --添加集合
2.删除
boolean remove(Ooject obj); --删除
boolean remove(Collection coll) --删除集合
void clear() --移除所有内容
3.判断
boolean contains(object obj); --判断些集合指定的元素,则返回true
boolean containsAll(Collection coll) --判断些集合指定的合集,则返回true
boolean isEmpty(): --判断集合中是否有元素。
4.获取:
int size(); --返回集合中的元素数
Iterator iterator(); --取出元素的方式:迭代器
5.其他:
boolean retainAll(Collection coll) --取交集(1,2,5; 2,4; 取2)
Object[] toArray(): --将集合转成数组。
3.List
除了继承自Collection的方法,还包括:
1.添加
add();
add(int index, T t);
addAll(Collection);
addAll(int index, Collection);
2.删除
remove(int index); --根据角标删除元素
remove(T t); --根据元素内容删除元素
3.修改
set(int index, T t); --将第index上的元素替换成t
4.查找
get(int index); --根据角标找到对应的元素
indexOf(T t); --根据元素找到对应的角标
5.将集合转化为对象数组
toArray(); --将集合转化成Object数组并返回
list.toArray(new String[list.size()]); --将集合元素放入**newString[list.size()**中然后返回
本文介绍了Java集合框架中的Iterable、Collection和List接口。Iterable是顶级接口,用于通过迭代器遍历元素;Collection是高度抽象的集合接口,包含基本的集合操作;List是有序集合,允许元素重复并具有索引。文章还列举了这些接口中的常用方法,如添加、删除、判断和获取元素等。

456

被折叠的 条评论
为什么被折叠?



