集合框架主要包括两部分,一部分是集合Collection,用来存储元素集合,另一种是Map,一种以Key-Value形式的特殊集合。Collection是一个接口,其子类型有List、Set。框架中最常用的有ArrayList,LinkedList,HashSet,LinkedHashSet,TreeSet,HashMap,LinkedHashMap,TreeMap等。
ArrayList和LinkedList:
ArrayList:
- 在内存中分配连续的空间,实现了长度可变的数组
- 优点:遍历元素和随机访问元素的效率比较高
- 缺点:添加和删除需大量移动元素效率低,按照内容查询效率低
LinkedList:
- 在内存中分配不连续空间,长度不固定。
- 优点:添加,删除效率较高,不需要移动其他元素
- 缺点:遍历元素和随机访问元素的效率低
Set
set集合特点:无序,值唯一(不重复)。
HashSet:
使用HashTable存储数据,增删改查速度快,无序。
LinkedHashSet:
在HashSet的基础上增加了链表管理数据,有序(插入数据的顺序)。
TreeSet:
使用红黑树存储数据,查询速度比List快,但没HashSet快。有序(自然顺序,可以使用Comparator改写排列顺序,存储对象时必须改写比较方法)
示例:使用三种Set存储学生信息。(这里学生对象的创建就不写了)
public class SetTest3 {
public static void main(String[] args) {
// Set<Student> list = new HashSet<>();
// Set<Student> list = new LinkedHashSet<>();
//在使用TreeSet存储学生信息时必须改写compare方法
Set<Student> list = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student stu1, Student stu2) {
return -(stu1.score - stu2.score);
}
});
Student stu1 = new Student("zzl", 18, 100, 1);
Student stu2 = new Student("zzl1", 20, 900, 2);
Student stu3 = new Student("zzl2", 19, 1000, 3);
Student stu4 = new Student("zzl3", 18, 10000, 4);
Student stu5 = new Student("zzl", 18, 10, 5);
list.add(stu1);
list.add(stu2);
list.add(stu3);
list.add(stu4);
list.add(stu5);
System.out.println(list.size());
for (Student student : list) {
System.out.println(student);
}
}
}
Map
Map集合是以Key-Value的形式存储数据。Key无序,唯一。
HashMap:
采用Hashtable哈希表存储结构,添加速度快,查询速度快,删除速度快。无序。
LinkedHashSet:
在HashMap基础上用链表结构,Key有序(插入顺序)
TreeMap:
使用红黑树存储数据,查询速度比List快,但没HashSet快。Key有序(Key值的自然顺序,可以改写)
示例:存储Student对象
public class MapTest {
public static void main(String[] args) {
Student stu1 = new Student("zzl", 18, 100, 1);
Student stu2 = new Student("zzl1", 18, 90, 2);
Student stu3 = new Student("zzl2", 18, 80, 3);
Student stu4 = new Student("zzl3", 18, 70, 4);
Student stu5 = new Student("zzl4", 18, 60, 5);
// Map<Integer, Student> map = new HashMap<Integer,Student>();
// Map<Integer, Student> map = new LinkedHashMap<Integer,Student>();
Map<Integer, Student> map = new TreeMap<Integer,Student>();
map.put(stu1.getSno(), stu1);
map.put(stu2.getSno(), stu2);
map.put(stu3.getSno(), stu3);
map.put(stu4.getSno(), stu4);
map.put(stu5.getSno(), stu5);
System.out.println(map);
//迭代器
Set<Integer> keySet = map.keySet();
Iterator<Integer> it = keySet.iterator();
while (it.hasNext()) {
int key = (int) it.next();
System.out.println(key+"-->"+map.get(key));
}
System.out.println("=======================");
Set<Entry<Integer, Student>> entrySet = map.entrySet();
for (Entry<Integer, Student> entry : entrySet) {
System.out.println(entry);
}
}
}