JAVA 集合类1-List接口与Set接口

一.集合概述

JAVA语言的java.util包中提供了一些集合类,这些集合类也被被称为容器。

集合与数组的区别:

1.数组长度时固定的,集合的长度时可变的;

2.数组用来存放基本类型数据,集合用来存放对象的引用。

二.集合的分类

1.常用的集合有LIst集合,Set集合,Map集合。其中List与Set实现了Collection接口;

2.Collection接口是根接口,构成Collection的单位称为元素,Colletion接口通常不能直接使用,由List与Set进行实现;

三.List接口

1.List接口继承了Collection接口,包含了Collection中所有的方法,因为List时列表类型,所以元素有顺序,可以重复。List接口还有一些适用于自身的常用方法。

2.List接口的子类常用的分为ArrayList实现类和LinkedList实现类。

ArrayList实现类与LinkedList实现类的区别:

  • ArrayList是以数组为底层的实现机制,特点是查询速度快, 但是增删改效率低。

  • LinkedList是以链表为底层的实现机制,特点是查询速度慢, 增删改的效率高。

3.常用List接口方法

List集合以线性方式存储对象,因此可以通过对象的索引来操作对象。

public class Test{
    
    public static void main(String[] args) {
        List list1 = new ArrayList();  //创建一个List型集合
        list1.add(123);  //向集合中添加对象
        list1.add(1,"abc");  //向集合中的指定索引位置添加对象
        list1.add(new Person());
        System.out.println(list1);  //打印添加后的集合;打印结果:[123, abc, Person [name=null]]
        System.out.println(list1.size());  //获取集合中的元素个数;打印结果:3
        System.out.println(list1.isEmpty());  //判断集合中是否有元素;打印结果:false
        System.out.println(list1.indexOf(123));  //获取该对象第一次出现的索引位置,没有返回-1;打印结果:0
        System.out.println(list1.lastIndexOf("abc"));  //获取该对象最后一次出现的索引位置,没有返回-1;打印结果:1
        list1.set(1, "abcd");  //替换指定索引位置的元素对象;
        System.out.println(list1);  //打印结果:[123, abcd, Person [name=null]]
     System.out.println(list1.retainAll(list1));  //保留两个集合的交集,内容不相同返回true,否则返回false;打印结果:false
    
System.out.println(list1.equals(list1));  //判断两个集合是否相等,相等返回true,否则返回false;打印结果:true; Object o1 = list1.addAll(0,list1);  //向集合中的指定索引位置添加指定的集合对象; System.out.println(list1);  //打印结果:[123, abcd, Person [name=null], 123, abcd, Person [name=null]] System.out.println(list1.get(0));  //获取指定索引位置的对象;打印结果:123 Object o2 = list1.remove(1);  //删除指定索引位置的对象;打印结果:[123, Person [name=null], 123, abcd, Person [name=null]] System.out.println(list1); list1.remove(new Person());  //删除集合中的Person对象,需要重写equals方法;打印结果:[123, 123, abcd, Person [name=null]] System.out.println(list1); list1.remove(new Integer(123));  //删除集合中数字对象,需要对数字进行包装;打印结果:[123, abcd, Person [name=null]] System.out.println(list1); } }

四.Set接口常用方法

1.Set接口同样继承了Collection接口,包含了Collection中的所有方法,没有自己单独的方法,元素没有顺序,不可以重复。

2.Set接口下常用的子类分为HashSet和TreeSet两类,其中HashSet实现类是以哈希码为底层的实现机制,在添加相同成员变量的元素时需要重写哈希码和equals方法,否则程序会认为两个元素不相同。

public static void main(String[] args) {
        
        Set set1 = new HashSet();  //创建一个Set型集合;
        set1.add(Object );  //如果集合中不存在此元素,则添加此元素;
        set1.addAll(Collection);  //将参数集合中所有元素添加到此集合的尾部;
        set1.remove(Object);  //移除指定对象;
        set1.removeAll(Collection);  //保留非交集;
        set1.retainAll(Collection);  //保留交集;
        set1.clear();  //清除集合中的所有元素;
        set1.size();  //获取集合中的元素个数;
        set1.isEmpty();  //判断集合中是否有元素;
        set1.iterator();  //获取该集合元素上进行迭代的迭代器;        
    }
原文地址:https://www.cnblogs.com/wyc1991/p/9024103.html