• JAVA中Colllection的基本功能


    Collection中的add方法:

    代码:

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Collection c=new ArrayList();//父类引用指向子类对象。这里是一个List的集合。
            boolean b1=c.add(new Student("zz",15));
            boolean b2=c.add(new Student("zz",15));
            System.out.println(b1);
            System.out.println(b2);
            
            System.out.println(c);
            

        }

    运行结果:

    true
    true
    [Student [name=zz, age=15], Student [name=zz, age=15]]

    需要注意的是,在调用Collection的add方法时,List允许加入多条相同数据,无论你加入什么,返回值一定为true.而Set不同,它不允许集合中存在相同数据,如果存在相同数据就会返回flase。ArryList的父类的父类,重写了toString 方法,输出对象不是Object类中的toStrng方法。

    Collection 中的remove方法:

    代码:    public static void main(String[] args) {
            // TODO Auto-generated method stub
            Collection c=new ArrayList();
            c.add("a");
            c.add("b");
            c.add("c");
            c.add("d");
            c.remove("b");
            System.out.println(c);

        }

    运行结果:

    [a, c, d]

    很显然,调用Collection中的remove方法能够删除指定元素。

    Collection中的clear方法。

    代码:    public static void main(String[] args) {
            // TODO Auto-generated method stub
            Collection c=new ArrayList();
            c.add("a");
            c.add("b");
            c.add("c");
            c.add("d");
    //        c.remove("b");
            c.clear();
            System.out.println(c);

        }
    运行结果:
    []
    需要注意的是,清空了集合,打印的方法中默认返回的就是"[]"。

    Collection中的contains方法。

    代码:

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Collection c=new ArrayList();
            c.add("a");
            c.add("b");
            c.add("c");
            c.add("d");
    //        c.remove("b");
    //        c.clear();
            System.out.println(c.contains("a"));
            System.out.println(c.contains("z"));
            System.out.println(c);

        }

    运行结果:

    true
    false
    [a, b, c, d]

    调用contains方法判断集合中是否包含,包含为true,不包含为false。

    Collection中判断是否为空,isEmpty()。

    Collection中查看元素个数,size()。这里就不一一举例。

  • 相关阅读:
    python类的__repr__方法
    元素定位之css选择器(1)
    selenium-find_element相关内容
    selenium-模块概述(1)
    元素定位之css选择器(2)
    css笔记
    html笔记
    html、css、javascript之间的关系
    去除提示“Chrome正在受到自动软件的控制”
    Python3+RobotFramework+pycharm环境搭建
  • 原文地址:https://www.cnblogs.com/lovelyYakir/p/5561522.html
Copyright © 2020-2023  润新知