Java——集合工具类(Collections工具类、Stack子类)

目录

1、Collections工具类

2、Stack子类


1、Collections工具类

Collections是专为集合服务的工具类,可以进行List、Set、Map等集合的操作,比较有用 的方法如下:

1)批量添加 public static <T> boolean addAll(@RecentlyNonNull Collection<? super T> c, @RecentlyNonNull T... elements)

2)反转:public static void reverse(@RecentlyNonNull List<?> list)

3)升序:public static <T extends Comparable<? super T>> void sort(@RecentlyNonNull List<T> list)

        List<String> all =new ArrayList<>();
//        all.add("hello");
//        all.add("world");
//        all.add("nice");
        Collections.addAll(all,"hello","world","nice");
        System.out.println(all);
        Collections.reverse(all);
        System.out.println(all);
        Collections.sort(all);
        System.out.println(all);

注意Collection与Collectons的区别:

  • Collection是集合操作的父接口,可以保存单值数据;
  • Collections是一个集合的操作工具类,可以操作List、Set、Map集合;

2、Stack子类

Stack是栈的数据结构实现,是一种先进后出的数据结构,如文本编辑的撤销就是基于栈的操作。Stack是Vector的子类。

Stack自己的处理方法:入栈:push,出栈:pop

        Stack<String> stack = new Stack<>();
        stack.push("A");
        stack.push("B");
        stack.push("C");
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());

该类了解即可,栈就是先进后出,字符串的反转操作,实际都是将字符入栈,而后再出栈实现的。

发布了86 篇原创文章 · 获赞 53 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/w464960660/article/details/104858503