Collection接口
创建集合的格式:
Collection<元素类型> 变量名 = new ArrayList<元素类型>();
方式2:Collection 变量名 = new ArrayList();
Collection接口中的方法
添加元素:add("a");
//判断集合中是否包含某元素:contains("b");
删除元素:remove("a");
集合元素长度:size();
清除所有元素:clear();
例:
1 public class Demo02 {
2 public static void main(String[] args) {
3 Collection<String> col=new ArrayList<String>();
4 col.add("a");
5 col.add("b");
6 System.out.println(col);
7 //col.clear();
8 //System.out.println(col);
9 //判断集合中是否包含某元素
10 boolean flag=col.contains("b");
11 System.out.println(flag);
12 //删除元素
13 col.remove("a");
14 System.out.println(col);
15 //遍历需向下转型
16 ArrayList<String> arr=(ArrayList<String>)col;
17 for (int i = 0; i < arr.size(); i++) {
18 System.out.println(arr.get(i));
19 }
20 }
21 }
知识兔Iterator迭代器
hasNext()方法:用来判断集合中是否有下一个元素可以迭代。如果返回true,说明可以迭代。
next()方法:用来返回迭代的下一个元素,并把指针向后移动一位。
例:
1 public class Demo03 {
2 public static void main(String[] args) {
3 Collection<String> col=new ArrayList<String>();
4 col.add("aaa");
5 col.add("bbb");
6 col.add("ccc");
7 //迭代器遍历
8 Iterator<String> it=col.iterator();
9 //判断集合中下个元素是否有值
10
11 while(it.hasNext()){
12 String a=it.next();
13 if(a.equals("bbb")){
14 System.out.print(a);
15
16 }}
17 }
18 }
知识兔如图所示:
增强for遍历
格式:
for(数据类型 变量名 : 容器) {
//...
}
增强for遍历集合,本质是迭代器
增强for的优点和缺点
优点: 语法更加的简洁。 省略了索引的操作。
缺点: 在循环中拿不到索引,所以如果要对索引进行操作,还需要使用普通for循环。
应用:
1 public class Demo05 {
2 public static void main(String[] args) {
3 Collection<Person> col=new ArrayList<Person>();
4 col.add(new Person("熊大",18));
5 col.add(new Person("熊二",19));
6 //增强for遍历
7 for(Person p:col){
8 System.out.println(p);
9 }
10 //数组
11 int[] arr={1,5,5,3,6,9,7,5};
12 for(int i:arr){
13 System.out.print(i);
14 }
15 }
16 }
知识兔如图所示: