java 集合类Collection
java 的集合类的结构图如下,以下涵盖了所有的集合类和他的实现类

1.下面来讲讲collection 集合类的方法。(由于collection 是最顶层的接口,所有它下面的实现类都拥有它的方法)
public class TestCollection {
public static void main(String[] args) {
//这里是用多态,使接口指向了实现类;
// Collection<String> collection= new ArrayList<String>() ;
//在这里我们把实现改了,依旧可以使用。因为下面的方法都是collection类的方法
Collection<String> collection= new LinkedList<>() ;
//删除的方
collection.remove("xiaoming");
//添加元素的方法
collection.add("xiaoming");
collection.add("luffy");
collection.add("sanzhi");
collection.add("zero");
//判断集合内是否包含某值
boolean bool=collection.contains("zero");
//获取集合的元素个数
int size=collection.size();
//判断集合是否为空
boolean isEmp=collection.isEmpty();
//把collection 转为数组
Object[] collStr=collection.toArray();
for (int i = 0; i <collStr.length ; i++) {
System.out.println("collStr:"+collStr[i]);
}
System.out.println("bool:"+bool);
System.out.println("collection:"+collection);
System.out.println("size:"+size);
System.out.println("isEmp:"+isEmp);
}
}
输出的结果是:
collStr:xiaoming
collStr:luffy
collStr:sanzhi
collStr:zero
bool:true
collection:[xiaoming, luffy, sanzhi, zero]
size:4
isEmp:false
2.1用迭代器的方式遍历出collection 的元素(collection 里面有个方法iterator返回一个 Iterato<E> 泛型)
2.2使用增强for循环来遍历(这个更加简单)
注意:增强for 循环只能遍历元素,不能再里面操作元素。而且他的目标只能是数组或者collection 类
测试代码如下
package com.collectiondo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class TestIterator {
public static void main(String[] args) {
Collection<String> coll=new ArrayList<>();
coll.add("海贼王");
coll.add("火影");
coll.add("进击的巨人");
coll.add("鬼灭之刃");
coll.add("死神");
//new 一个迭代器,用接口指向实现类
Iterator<String> iterator=coll.iterator();
while(iterator.hasNext()){
System.out.println("打印元素:"+iterator.next());
}
//使用增强for 循环
for(String name:coll){
System.out.println("打印元素:"+name);
}
} }
输出的结果为:
打印元素:海贼王
打印元素:火影
打印元素:进击的巨人
打印元素:鬼灭之刃
打印元素:死神

浙公网安备 33010602011771号