java中Collection集合常用的API

Collection集合特点:

List系列集合:添加的元素是有序,可重复,有索引。

如:ArrayList,LinekdList:有序,可重复,有索引

Set系列集合:添加的元素是无序,不重复,无索引

如:HashSet:无序,不可重复,无索引

LinkedHashSet:有序,不重复,无索引

TreeSet:按照大小默认升序排序,不重复,无索引

Collection中常用的API:

public interface Collection<E> 该类是一个接口类

boolean add(E e)

Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call.

添加成功返回trueAPI

void clear()

Removes all of the elements from this collection (optional operation). The collection will be empty after this method returns.

清空集合中的元素

boolean isEmpty()

Returns true if this collection contains no elements.

int size()

Returns the number of elements in this collection.

boolean contains(Object o)

Returns true if this collection contains the specified element.

boolean remove(Object o)

Removes a single instance of the specified element from this collection, if it is present (optional operation)

删除某个元素,如果有重复就删除第一个

Object[] toArray()

Returns an array containing all of the elements in this collection.

把集合转换成数组

boolean addAll(Collection<? extends E> c)

Adds all of the elements in the specified collection to this collection (optional operation).

java 复制代码
public class test {
    public static void main(String[] args) {
        Collection<String>c=new ArrayList<>();//多态
        //Collection是一个接口类,不能直接创建对象

        //1:add,成功返回true
        c.add("java1");
        c.add("java2");
        System.out.println(c);//[java1, java2]

        //2:clear
        c.clear();

        //3:isEmpty
        System.out.println(c.isEmpty());//true

        c.add("java1");
        c.add("java2");
        System.out.println(c.isEmpty());//false

        //size
        System.out.println(c.size());//2

        //contains
        System.out.println(c.contains("java1"));//true

        //remove
        c.add("java1");
        System.out.println(c);//[java1, java2, java1]
        c.remove("java1");
        System.out.println(c);//[java2, java1]//只删第一个(有重复)

        //toArray
       Object[] array = c.toArray();

        System.out.println(Arrays.toString(array));//[java2, java1]

        String []array2=c.toArray(new String[c.size()]);
        System.out.println(Arrays.toString(array2));

        System.out.println("---");

        //addAll
        Collection<String>c2=new ArrayList<>();
        c2.add("java3");
        c.addAll(c2);
        System.out.println(c);//[java2, java1, java3]


    }
}

Collection中的遍历方式:

1:迭代器

Collection获取迭代器:

Iterator<E> iterator()

Returns an iterator over the elements in this collection.

返回集合中的迭代器,默认是集合中的第一个元素

迭代器的方法:

E next()

获取当前位置的元素,并同时将迭代器对象移到下个一个元素的位置

boolean hasNext()

判断这个位置是否有元素

java 复制代码
public class test2 {
    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>();
        c.add("java1");
        c.add("java2");
        c.add("java3");
        Iterator<String> iterator = c.iterator();//获取集合中的迭代器
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }     
}

2:增强for循环

java 复制代码
public class test3 {
    public static void main(String[] args) {
        Collection<String>c=new ArrayList<>();
        c.add("java1");
        c.add("java2");
        c.add("java3");
        //使用增强for循环的方式
        for(String ele:c)
        {
            System.out.println(ele);
        }

        //普通的数组也可以使用
        String []names=new String[]{"hh","aa","bb"};
        for(String name:names)
        {
            System.out.println(name);

        }    }
}

3:Lambda表达式遍历集合

default void forEach(Consumer<? super T> action)

java 复制代码
public class test4 {
    public static void main(String[] args) {
        Collection<String> c=new ArrayList<>();
        c.add("java1");
        c.add("java2");
        c.add("java3");
        //default void forEach(Consumer<? super T> action) {
        //Consumer是一个抽象类,所以我们使用匿名对象
        c.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        });

        c.forEach(s-> System.out.println(s));
        //out是一个对象,且前后参数一致,可以使用实例方法引用
        c.forEach(System.out::println);
    }
}

遍历集合中的自定义对象

java 复制代码
public class movies {
    private String name;
    private double score;

    public movies() {
    }

    public movies(String name, double score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "movies{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }
}
java 复制代码
public class testMovies {
    public static void main(String[] args) {
        Collection <movies>c=new ArrayList<>();
        c.add(new movies("hhh",9.5));
        c.add(new movies("aaa",9.8));
        c.add(new movies("ccc",7.1));

        System.out.println(c.toString());//直接打印的是三个电影的地址
        //[com.he.colletion.movies@2f4d3709, com.he.colletion.movies@4e50df2e, com.he.colletion.movies@1d81eb93]

        //可以在movies中重写toString方法
        //[movies{name='hhh', score=9.5}, movies{name='aaa', score=9.8}, movies{name='ccc', score=7.1}]
//1
        for(movies m : c)
        {
            System.out.println(m);
        }
//2
        c.forEach(new Consumer<movies>() {
            @Override
            public void accept(movies movies) {
                System.out.println(movies);
            }
        });
        c.forEach(movies -> {
            System.out.println(movies);
        });
        c.forEach(System.out::println);
//3
        Iterator<movies> iterator = c.iterator();
        while(iterator.hasNext())
        {
            System.out.println(iterator.next());
        }

    }
}

注意:集合中存储的是对象的地址

相关推荐
互联网全栈架构22 分钟前
遨游Spring AI:第一盘菜Hello World
java·人工智能·后端·spring
qq_4298796722 分钟前
省略号和可变参数模板
开发语言·c++·算法
Kaede61 小时前
如何应对Linux云服务器磁盘空间不足的情况
linux·运维·服务器
优秀的颜1 小时前
计算机基础知识(第五篇)
java·开发语言·分布式
BillKu1 小时前
Java严格模式withResolverStyle解析日期错误及解决方案
java
CodeWithMe1 小时前
【C/C++】std::vector成员函数清单
开发语言·c++
uyeonashi1 小时前
【QT控件】输入类控件详解
开发语言·c++·qt
网安INF1 小时前
ElGamal加密算法:离散对数难题的安全基石
java·网络安全·密码学
iCxhust2 小时前
Prj10--8088单板机C语言8259测试(1)
c语言·开发语言
AWS官方合作商2 小时前
在CSDN发布AWS Proton解决方案:实现云原生应用的标准化部署
java·云原生·aws