集合、迭代器

集合:

集合是java中提供的一种容器,可以用来存储多个数据。

数组的长度是固定的。集合的长度是可变的。集合中存储的元素必须是引用类型数据

Collection接口常用的子接口有:List接口、Set接口

List接口常用的子类有:ArrayList类、LinkedList

Set接口常用的子类有:HashSet类、LinkedHashSet

 

import java.util.ArrayList;

public class Demo01 {

  public static void main(String[] args) {
  /*ArrayList<Integer> arr=new ArrayList<Integer>();
  arr.add(1);
  arr.add(0);*/
  ArrayList<Person> arr=new ArrayList<Person>();
  arr.add(new Person("小红帽",25));
  arr.add(new Person("大灰狼",24));
  arr.add(new Person("光头强",21));
  for(int i=0;i<arr.size();i++){
    System.out.println(arr.get(i));
    }
  }

}

import java.util.ArrayList;
import java.util.Collection;

public class Demo02 {
public static void main(String[] args) {
  Collection<Integer> col=new ArrayList<Integer>();
  col.add(10);
  col.add(20);
  //清空集合
  //col.clear();
  //判断集合中是否包含该元素
  boolean flag=col.contains(20);
  System.out.println(flag);
  //根据值删除集合中的元素
  col.remove(10);
  //遍历
  if(col instanceof ArrayList){
    ArrayList<Integer> arr=(ArrayList<Integer>)col;
    for(int i=0;i<arr.size();i++){
      System.out.println(arr.get(i));
    }
  }
  //将集合转为数组
  Object[] obj=col.toArray();
  for(int i=0;i<obj.length;i++){
    System.out.println(obj[i]);
    }
  }
}

 迭代器:

在取元素之前先要判断集合中有没有元素,如果有,就把这个元素取出来,继续在判断,如果还有就再取出出来,这种取出方式专业术语称为迭代。

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo04 {
  public static void main(String[] args) {
    Collection<Integer> col=new ArrayList<Integer>();
    col.add(10);
    col.add(20);
    col.add(30);
    //用迭代器遍历
    //获取迭代器对象
    Iterator<Integer> it=col.iterator();
    //判断集合中是否有下一个元素
    while(it.hasNext()){
      System.out.println(it.next());
    }
  }
}

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo05 {
  public static void main(String[] args) {
    Collection col=new ArrayList();
    col.add("abc");
    col.add("bcd");
    col.add("efg");
    //获取迭代器对象
    Iterator it=col.iterator();
    //判断集合中是否有元素
    while(it.hasNext()){
    //获取每个元素
    Object s=it.next();
    //判断元素是否是String类型
    if(s instanceof String){
      //向下转型
      String str=(String)s;
      //调用子类独有的方法
      System.out.println(str.length());
      }
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/boss-H/p/10957174.html
今日推荐