package com.java; import org.junit.Test; import java.util.*; public class ColllectionTest { @Test public void colllectionTest() { //接口类型的引用指向实现类型的对象,形成多态 Collection collection = new ArrayList(); System.out.println(collection);//[] boolean b = collection.add("one");//[one] System.out.println("b = " + b);//true collection.add(2); System.out.println(collection);//[one, 2] collection.add('a'); System.out.println(collection);//[one, 2, a] collection.add("打开"); System.out.println(collection);//[one, 2, a, 打开] System.out.println("========="); //将集合转换成数组 Object[] objects = collection.toArray(); //遍历数组中的元素,方法一 for (int i = 0; i < objects.length; i++){ System.out.println(objects[i]); } //将数组转换为集合 List objects1 = Arrays.asList(objects);//List是Object类型 System.out.println(objects1); System.out.println("========="); //迭代器遍历集合中的元素,方法二 Iterator it = objects1.iterator(); while(it.hasNext() == true) { /*Object obj = it.next(); System.out.println(obj);*/ System.out.println(it.next()); } System.out.println("----------------------------------"); //遍历集合中的元素方法三 //加强for循环只能迭代Collection和数组 for (Object o : objects1 ){ System.out.println(o); } } }
04-23
4063
04-07
3912