Java集合框架【二容器(Collection)[Vector容器类]】

╰+哭是因爲堅強的太久メ 2024-03-31 08:26 169阅读 0赞

文章目录

  • 三 Vector容器类
    • 3.5 Vector容器类
      • 3.5.1 Vector的使用
      • 3.5.2 Stack容器
        • 3.5.3.1 Stack容器介绍
        • 3.5.3.2 操作栈方法
      • Stack的使用案例

三 Vector容器类

3.5 Vector容器类

  • Vector底层是用数组实现的,相关的方法都加了同步检查,因此“线程安全,效率低”比如,indexOf方法就增加了synchronized同步标记。

3.5.1 Vector的使用

  • Vector的使用与ArrayList是相同的,因为他们都实现了List接口,对List接口中的抽象方法做了具体实现。

    /**

    • @author 缘友一世
    • date 2022/11/18-14:10
      */
      public class VectorTest {

      public static void main(String[] args) {

      1. Vector<String> v = new Vector<>();
      2. v.add("aaa");
      3. v.add("bbb");
      4. v.add("ccc");
      5. for(int i=0;i<v.size();i++) {
      6. System.out.print(v.get(i)+" ");
      7. }

      }
      }

在这里插入图片描述

3.5.2 Stack容器

3.5.3.1 Stack容器介绍
  • Stack栈容器,是Vector的一个子类,它实现了一个标准的后进先出(LIFO:LastinFristOut)的栈。
  • Stack特点是:后进先出。它通过5个操作方法对Vector进行扩展,允许将向量视为堆栈。
3.5.3.2 操作栈方法

在这里插入图片描述

  1. /**
  2. * @author 缘友一世
  3. * date 2022/11/18-14:22
  4. */
  5. public class StackTest {
  6. public static void main(String[] args) {
  7. Stack<String> stack = new Stack<>();
  8. stack.push("521");
  9. stack.push("1314");
  10. stack.push("999");
  11. System.out.println(stack.empty());
  12. System.out.println(stack.peek());
  13. System.out.println(stack.search("521"));
  14. for(String s: stack) {
  15. System.out.println(s);
  16. }
  17. }
  18. }

在这里插入图片描述

Stack的使用案例

  1. /**
  2. * @author 缘友一世
  3. * date 2022/11/18-14:29
  4. */
  5. public class StackApplication {
  6. public static void main(String[] args) {
  7. String str="...{...[...(....)...]...}..(....)..[...]...";
  8. Stack<String> stack = new Stack<>();
  9. //假设修正法
  10. boolean flag=true;//假设是匹配的
  11. //拆分字符和获取字符
  12. for(int i=0;i<str.length();i++) {
  13. char c=str.charAt(i);
  14. if(c=='{') {
  15. stack.push("}");
  16. }else if(c=='[') {
  17. stack.push("]");
  18. }else if(c=='(') {
  19. stack.push(")");
  20. }
  21. if(c=='}'||c==']'||c==')') {
  22. if(stack.empty()) {
  23. //如果是空栈就进行修正
  24. flag=false;
  25. break;
  26. }
  27. String x=stack.pop();
  28. //如出栈的字符与遇到的字符不同,就进行修正
  29. if(x.charAt(0)!=c) {
  30. flag=false;
  31. break;
  32. }
  33. }
  34. }
  35. //如果最终匹配所有字符之后,栈不为空,说明字符不对称
  36. if(!stack.empty()) {
  37. flag=false;
  38. }
  39. System.out.println(flag);
  40. }
  41. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,169人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java容器集合

    一、基本概念 Java容器类类库的用途是“持有对象”,并将其划分为两个不同的概念: 1)Collection:一个独立元素的序列,这些元素都服从一条或者多条规则。 Li