一、Collection接口
Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements)。一些Collection允许相同的元素而另一些不行。一些能排序而另一些不行。
JavaSDK不提供直接继承自Collection的类,Java SDK提供的类都是继承自Collection的“子接口”如List和Set。
Collection 接口的接口 对象的集合(单列集合)
├——-List 接口:元素按进入先后有序保存,可重复
│—————-├ LinkedList 接口实现类, 链表, 插入删除, 没有同步, 线程不安全
│—————-├ ArrayList 接口实现类, 数组, 随机访问, 没有同步, 线程不安全
│—————-└ Vector 接口实现类 数组, 同步, 线程安全
│ ———————-└ Stack 是Vector类的实现类
└——-Set 接口: 仅接收一次,不可重复,并做内部排序
├—————-└HashSet 使用hash表(数组)存储元素
│————————└ LinkedHashSet 链表维护元素的插入次序
└ —————-TreeSet 底层实现为二叉树,元素排好序
- public class PracticeCollection {
-
- /**
- * 向集合中插入重复的值
- * @return
- */
- public static ArrayList
makeList(){ - ArrayList
testList=new ArrayList<>(); - testList.add("tfq");
- testList.add("tfq");
- testList.add("tfq");
- testList.add("tfq1");
- testList.add("tfq1");
- return testList;
- }
-
- /**
- * 不能存入重复的值到Set
- * @return
- */
- public static Set
makeSet(){ - Set
testList=new HashSet<>(); - testList.add("tfq");
- testList.add("tfq");
- testList.add("tfq");
- testList.add("tfq1");
- testList.add("tfq1");
- return testList;
- }
-
-
- public static void main(String[] args) {
- System.out.println("ArrayList打印:------>");
- makeList().stream().forEach(x->{
- System.out.println(x);
- });
-
- System.out.println("HashSet打印:------>");
- makeSet().stream().forEach(x->{
- System.out.println(x);
- });
-
- }
-
- }
- public class PracticMap {
-
- /**
- * 接口实现类 ,没有同步, 线程不安全,通过Collections工具类解决集合类HashMap线程不安全问题
- *
- * @return
- */
- public static Map
makeHashMap() { - Map
map = Collections.synchronizedMap(new HashMap<>()); - //模拟30个线程,往HashMap集合中添加数据
- for(int i = 1; i <= 30; i++) {
- new Thread(() -> {
- map.put(Thread.currentThread()
- .getName(), UUID.randomUUID()
- .toString()
- .substring(0, 8));
- System.out.println(map);
- }).start();
- }
- return map;
- }
-
- /**
- * 通过JUC包下的并发集合类解决HashMap线程不安全问题,jdk1.8 API中的并发集合类截图如下
- * @return
- */
- public static Map
makeConcurrentHashMap() { - Map
map =new ConcurrentHashMap<>(); - //模拟30个线程,往HashMap集合中添加数据
- for(int i = 1; i <= 30; i++) {
- new Thread(() -> {
- map.put(Thread.currentThread()
- .getName(), UUID.randomUUID()
- .toString()
- .substring(0, 8));
- System.out.println(map);
- }).start();
- }
- return map;
- }
-
-
- public static void main(String[] args) {
- makeConcurrentHashMap();
- }
-
- }