部分内容转自:https://blog.csdn.net/zzw1531439090/article/details/87872424
准备重新看看集合类中的好伙计们,先总体整理一下集合体系
总体结构
下图可以很清楚的说明
这张图初学者乍看可能觉得很复杂,咱们来理一理
在接口层,jdk主要定义了Map接口和Collection接口,然后分出若干子接口,以Collection接口为例,它的下层子接口有三个,分别是List ,Queue 和Set,然后在它们的基础上实现了ArrayList LinkedList ,DelayQueue等集合
这里先要温习一下队列和栈这两种数据接口,队列的特点是先进先出FIFO,而栈的特点是先进后出,又称压栈弹栈
比较有趣的是,你可以发现,各种set实现自Set接口,list实现自List接口,而它们有一个共同父接口,Collection,在java上讲它们其实可以规划为同一个类型,这也是为什么它们被称为“集合类”,所以它们还有一个很重要的特性,就是可以互相转换,list基于数组实现,所以可以和数组互转,直接将set或者list实例传递给对方的构造方法,就可以直接实现转换,这里要注意,若list中有重复数据如重复字符串,转成set后会被去重。
数组转Set
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
staffsSet.add("Mary"); // ok
staffsSet.remove("Tom"); // ok
List转数组
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
Object[] result = staffsList.toArray();
List转Set
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
Set result = new HashSet(staffsList);
Set转数组
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
Object[] result = staffsSet.toArray();
Set转List
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
List<String> result = new ArrayList<>(staffsSet);