JAVA 集合类1

一.集合概述

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);//打印添加后的集合;
        System.out.println(list1.size());//获取集合中的元素个数;
        System.out.println(list1.isEmpty());//判断集合中是否有元素
        System.out.println(list1.indexOf(123));//获取该对象第一次出现的索引位置,没有返回-1;
        System.out.println(list1.lastIndexOf("abc"));//获取该对象最后一次出现的索引位置,没有返回-1;
        list1.set(1, "abcd");//替换指定索引位置的元素对象;
        System.out.println(list1);
     System.out.println(list1.retainAll(list1));//List内容改变返回true,否则返回false;
    
System.out.println(list1.equals(list1));//判断两个集合是否相等,相等返回true,否则返回false; Object o1 = list1.addAll(0,list1);//向集合中的指定索引位置添加指定的集合对象; System.out.println(list1); System.out.println(list1.get(0));//获取指定索引位置的对象; Object o2 = list1.remove(1);//删除指定索引位置的对象; System.out.println(list1); list1.remove(new Person());//删除集合中的Person对象,需要重写equals方法; System.out.println(list1); list1.remove(new Integer(123));//删除集合中数字对象,需要对数字进行包装; System.out.println(list1); } }

猜你喜欢

转载自www.cnblogs.com/wyc1991/p/9024103.html