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());
        }

    }
}

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

相关推荐
风象南18 分钟前
SpringBoot集成MyBatis的SQL拦截器实战
java·spring boot·后端
fire-flyer1 小时前
Spring Boot 源码解析之 Logging
java·spring boot·spring·log4j·logging
码农101号1 小时前
Linux中Docker Compose介绍和使用
linux·运维·docker
papership1 小时前
【入门级-C++程序设计:12、文件及基本读写-文件的基本概念&文本文件的基本操作】
开发语言·c++·青少年编程
SaleCoder2 小时前
用Python构建机器学习模型预测股票趋势:从数据到部署的实战指南
开发语言·python·机器学习·python股票预测·lstm股票模型·机器学习股票趋势
KoiHeng2 小时前
部分排序算法的Java模拟实现(复习向,非0基础)
java·算法·排序算法
deeper_wind5 小时前
keeplived双击热备配置
linux·运维·网络
cui_hao_nan6 小时前
JVM——如何对java的垃圾回收机制调优?
java·jvm
GoldKey7 小时前
gcc 源码阅读---语法树
linux·前端·windows
熟悉的新风景7 小时前
springboot项目或其他项目使用@Test测试项目接口配置-spring-boot-starter-test
java·spring boot·后端