Java中集合可以说是最常用的一部分内容,集合呢一共也就两部分,分别是Collection和Map
其中Collection中有List和Set,其中List集合中的元素可以重复,Set集合中的元素不可重复(通过hashcode和equals函数保证)
ArrayList内部结构是数组,查询快,增删慢,存储顺序和输出顺序相同
LinkedList内部结构是链表,查询慢,增删快,存储顺序和输出顺序相同
HashSet内部结构是哈希表,是无序的(不一定会自动排好顺序)
TreeSet内部结构是红黑树,是有序的
LinkedHashSet存储顺序和输出顺序相同
HashMap也就是键值对,其中键不可重复,键是唯一的
样例演示:
import java.util.*;
public class Test1 {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
LinkedList<Integer> link = new LinkedList<>();
HashSet<Integer> hs = new HashSet<>();
TreeSet<Integer> ts = new TreeSet<>();
LinkedHashSet<Integer> lhs = new LinkedHashSet<>();
HashMap<Integer, String> hm = new HashMap<>();
arr.add(1);
arr.add(5);
arr.add(3);
arr.add(1);
arr.add(7);
for (Integer a : arr) {
System.out.print(a + " ");
}
System.out.println();
link.add(2);
link.add(7);
link.add(5);
link.add(2);
for (Integer l : link) {
System.out.print(l + " ");
}
System.out.println();
hs.add(1);
hs.add(9);
hs.add(5);
for (Integer h : hs) {
System.out.print(h + " ");
}
System.out.println();
ts.add(1);
ts.add(9);
ts.add(5);
for (Integer t : ts) {
System.out.print(t + " ");
}
System.out.println();
lhs.add(1);
lhs.add(9);
lhs.add(5);
for (Integer l : lhs) {
System.out.print(l + " ");
}
System.out.println();
hm.put(3, "a");
hm.put(2, "b");
hm.put(5, "c");
for (Map.Entry<Integer, String> entry : hm.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
样例输出: