* 一,集合框架的概述 * 1.集合,数组都是对多个数据进行存储操作的结构,简称java容器 * 2.数组在存储多个数据方面的特点 * 一旦初始化以后,其长度就确定 * 数组一旦定义好,其元素的类型也就确定了,只能操作指定类型的数据了 * 比如 String[] arr; int[] arr1;Object[] arr2 *
Collection接口中的常用方法
package day23.demo1;
import com.sun.javaws.IconUtil;
import org.junit.Test;
import java.util.*;
/**
*
* */
public class CollectionTest {
@Test
public void test1(){
Collection coll = new ArrayList();
// add(Object e) 将元素e添加到集合coll中
coll.add("aa");
coll.add("bb");
coll.add(123);
coll.add(new Date());
// size() 获取添加元素的个数
System.out.println(coll.size()); // 4
// addAll(Collection coll1) 将coll1集合中元素添加到当前的集合中
Collection coll1 = new ArrayList();
coll1.add(456);
coll1.add("CC");
coll1.addAll(coll);
System.out.println(coll1.size()); //6
System.out.println(coll);// [aa, bb, 123, Sat Oct 09 22:03:34 CST 2021]
// clear() 清空集合
// isEmpty() 判断当前集合是否为空
System.out.println(coll.isEmpty());
}
@Test
public void test2(){
// 向Collectin 接口的实现类的对象中添加数据obj时,要求obj所在类要重写equals()
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new String("Tom"));
coll.add(false);
coll.add(new Person("jerry",20));
// contains(Object obj)判断当前集合中是否包含obj
boolean contains = coll.contains(123);
System.out.println(contains); // true
System.out.println(coll.contains(new String("Tom"))); // true
// remove(Object obj)
//coll.remove(123);
// retainAll(Collection coll1) 交集 获取当前集合和coll1集合的交集,并返回给当前集合
//Collection coll1 = Arrays.asList(123,456,789);
//coll.retainAll(coll1);
System.out.println(coll);
// equals(Object obj) 想要返回true,需要当前集合和形参集合的元素都相同
// 集合转换数组
Object[] arr = coll.toArray();
for(int i = 0; i <arr.length;i++){
System.out.println(arr[i]);
}
// 数组转换为集合 集合调用Arrays类的静态方法asList()
List<String> list =Arrays.asList(new String[]{"aa","bb","cc"});
System.out.println(list); // [aa, bb, cc]
List<int []> arr1 = Arrays.asList(new int[]{123,456});
System.out.println(arr1); // [[I@1b9e1916]
}
}
使用Iterator遍历Collection