集合框架包含四个重要接口
Collection: 最基本的接口。元素的存放次序未作规定,是否包含重复对象也未作定义
Set: 扩展了Colletion接口,不允许有重复的对象。
List: 扩展了Collection接口,是一个有序聚集(对象按一定顺序存放),可按位置访问对象,允许重复
Collection: 最基本的接口。元素的存放次序未作规定,是否包含重复对象也未作定义
Set: 扩展了Colletion接口,不允许有重复的对象。
List: 扩展了Collection接口,是一个有序聚集(对象按一定顺序存放),可按位置访问对象,允许重复
Map: 键-值映射对
Collection是集合继承树中最顶层的接口,定义了15个常用的方法。
boolean add(Object element)
boolean remove(Object element)
int size()
boolean isEmpty() 判断是否存在元素
boolean contains(Object element)判断是否存在某元素
Iterator iterator()
Object[] toArray()
void clear()
boolean addAll(Collection collection)
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionTest {
public static void main(String[] args) {
//用泛型来声明一个集合
Collection<String> col=new ArrayList<String>();
col.add("南京");
col.add("无锡");
col.add("苏州");
col.add("扬州");
col.add("徐州");
System.out.println(col);
col.remove("苏州");
System.out.println(col);
System.out.println("判断集合里有多少个元素:"+col.size());
System.out.println("判断集合里是否存在元素:"+col.isEmpty());
System.out.println("判断集合里是否包含某个元素:"+col.contains("无锡"));
System.out.println("迭代遍历:");
Iterator it = col.iterator(); //迭代
while(it.hasNext())
{
System.out.println(it.next());
}
String[] city=col.toArray(new String[0]); //集合=>>数组,遍历
for(String s:city)
{
System.out.println(s);
}
//col.clear(); //清空集合
//System.out.println(col);
Collection<String> coll=new ArrayList<String>();
coll.add("巴黎");
coll.add("东京");
coll.add("旧金山");
col.addAll(coll); //集合相加
System.out.println(col);
Collection<Integer> s=new ArrayList<Integer>();
//自动装箱:基本类型自动转成包装类型。
s.add(1); //1,2自动装换成Integer类型
s.add(2);
//自动拆箱 包装类型自动转成基本类型
for(int i:s)
{
System.out.println(i);
}
System.out.println(s);
}
}