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

    }
}

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

相关推荐
逆小舟21 小时前
【Linux】人事档案——用户及组管理
linux·c++
青草地溪水旁21 小时前
pthread_mutex_lock函数深度解析
linux·多线程·pthread
喵手21 小时前
玩转Java网络编程:基于Socket的服务器和客户端开发!
java·服务器·网络
再见晴天*_*1 天前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
太空的旅行者1 天前
告别双系统——WSL2+UBUNTU在WIN上畅游LINUX
linux·运维·ubuntu
lqjun08271 天前
Qt程序单独运行报错问题
开发语言·qt
人工智能训练师1 天前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
灿烂阳光g1 天前
domain_auto_trans,source_domain,untrusted_app
android·linux
hdsoft_huge1 天前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
风中的微尘1 天前
39.网络流入门
开发语言·网络·c++·算法