为什么要使用集合
Java集合就是一个容器。面向对象语言对事物的体现都是以对象的形式存在,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式。集合只用于存储对象,集合长度是可变的,集合可以存储不同类型的对象。如果往集合里存放基本数据类型,在存取过程中会有个自动装箱和拆箱。
因为容器中数据结构不同,容器有很多种。不断地将共性功能向上抽取,形成了集合体系,称之为集合框架。
集合和数组的区别:
1:数组是固定长度的;集合可变长度的。
2:数组可以存储基本数据类型,也可以存储引用数据类型;集合只能存储引用数据类型。
3:数组存储的元素必须是同一个数据类型;集合存储的对象可以是不同数据类型。
在Java中提供了集合类来保存对象或者说是对象的引用,分为两类容器:Collecion和Map。
其中Collection包括:List[LinkedList,ArrayList,Vecto](必须按照插入顺序保存),Set[HashSet,TreeSet](保存的时候不能有重复元素),Queue(按照队列规则来确定对象产生的顺序)
Map:一组成对的“键值对”,允许用键来查找值;[HashMap,Hashtable,TreeMap,LinkedMap]
下面举一个简单的例子:
package testArrayList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
public class TestCollectionOutput {
static Collection<String> fill(Collection <String>collection) {
collection.add("cat");
collection.add("dog");
collection.add("pig");
collection.add("pig");
return collection;
}
static Map <String,Integer> fill(Map <String,Integer>map) {
map.put("cat", 1); //输入键和值
map.put("dog", 2);
map.put("pig", 3);
map.put("pig", 4);
return map;
}
public static void main(String[] args) {
System.out.println(fill(new ArrayList<String>())); //List以特定的顺序保存一组元素
System.out.println(fill(new LinkedList<String>()));
System.out.println(fill(new HashSet<String>())); //Set保存的元素不能重复
System.out.println(fill(new TreeSet<String>())); //按比较结果的升序保存对象
System.out.println(fill(new LinkedHashSet<String>())); //按照被添加的顺序保存对象
//Map在每个槽里保存了两个对象,键和之关联的值。Map会自动调节尺寸。Map中保存的顺序并不是他们插入的顺序
System.out.println(fill(new HashMap<String,Integer>())); //HashMap提供了最快的查询速度,没有按照明显的的顺序来保存其元素
System.out.println(fill(new TreeMap<String,Integer>())); //按照比较结果的升序来保存键
System.out.println(fill(new LinkedHashMap<String,Integer>())); //按照插入顺序保存键同时还保留了HashMap的查询速度
}
}
运行结果: