自学内容网 自学内容网

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). 

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

判断这个位置是否有元素 

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循环

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)

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

 遍历集合中的自定义对象

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

    }
}

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


原文地址:https://blog.csdn.net/luosuss/article/details/137474785

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!