java之List接口及泛型使用

List 接口

List 子接口

在这里插入图片描述

List 接口使用

  • public class Demo01 {
          
          
        /*
        List 子接口的使用
        特点:有序有下标  可以重复
         */
        public static void main(String[] args) {
          
          
    //        先创建集合对象
            List list = new ArrayList();
    //        添加元素
            list.add("苹果");
            list.add(0,"oppo");
            list.add("华为");
            System.out.println("元素个数:"+list.size());
            System.out.println(list.toString());
    //        删除元素
    //        list.remove("苹果");
    //        list.remove(0);
    //        System.out.println("元素个数:"+list.size());
    //        System.out.println(list.toString());
    //        遍历元素
    //        使用for遍历
            for (int i = 0;i < list.size();i++){
          
          
                System.out.println(list.get(i));
            }
    //        使用增强for
            for (Object object : list) {
          
          
                System.out.println(object);
    
            }
    //        使用迭代器
            Iterator it = list.iterator();
            while (it.hasNext()){
          
          
                System.out.println(it.next());
            }
    //        使用列表迭代器  和iterator的区别  listIterator可以向前或向后遍历,添加、删除、修改元素
            ListIterator lit= list.listIterator();
            System.out.println("从前往后");
            while (lit.hasNext()){
          
          
                System.out.println(lit.nextIndex()+":"+lit.next());
            }
            System.out.println("从后往前");
            while (lit.hasPrevious()){
          
          
                System.out.println(lit.previousIndex()+":"+lit.previous());
            }
    //        判断
            System.out.println(list.contains("苹果"));
            System.out.println(list.isEmpty());
    //        获取
            System.out.println(list.indexOf("华为"));
        }
    }
    
  • public class Demo02 {
          
          
        /*
        List 的使用
         */
        public static void main(String[] args) {
          
          
    //        创建集合
            List list = new ArrayList();
    //        添加数字数据
            list.add(20);
            list.add(30);
            list.add(40);
            list.add(50);
            list.add(60);
            list.add(70);
            System.out.println("元素个数:"+list.size());
            System.out.println(list.toString());
    //        删除操作
    //        list.remove((Object) 20);
    //        System.out.println("删除元素:"+list.size());
    //        System.out.println(list.toString());
    //        补充方法 返回子集合  含头不含尾
            List sublist = list.subList(1, 3);
            System.out.println(sublist.toString());
        }
    }
    

List 实现类

  • ArrayList[重点]:

    • 数组结构实现,查询快、增删慢;
    • JDK1.2版本,运行效率快 ,线程不安全
  • Vector:

    • 数组结构实现,查询快、增删慢;
    • JDK1.0版本,运行效率慢,线程安全
  • LinkedList:

    • 链式结构实现,增删快、查询慢

ArrayList 使用

  • public class Demo03 {
          
          
        /*
        ArrayList 的使用
        数组结构实现,查询快、增删慢;
         */
        public static void main(String[] args) {
          
          
    //        创建集合
            ArrayList arrayList = new ArrayList<>();
    //        添加元素
            Student s1 = new Student("刘德华", 20);
            Student s2 = new Student("成龙", 20);
            Student s3 = new Student("吴彦祖", 20);
            arrayList.add(s1);
            arrayList.add(s2);
            arrayList.add(s3);
            System.out.println("元素个数"+arrayList.size());
            System.out.println(arrayList.toString());
    //        删除元素
    //        arrayList.remove(new Student("成龙", 20));
    //        System.out.println("元素个数"+arrayList.size());//
    //        System.out.println(arrayList.toString());
    //        遍历元素  {重点}
    //        使用迭代器
            Iterator it = arrayList.iterator();
            while (it.hasNext()){
          
          
                Student s = (Student)it.next();
                System.out.println(s.toString());
            }
    //        列表迭代器
            ListIterator lit = arrayList.listIterator();
            System.out.println("--------------------------------");
            while (lit.hasNext()){
          
          
                Student s = (Student)lit.next();
                System.out.println(s.toString());
            }
    //        逆序
            while (lit.hasPrevious()){
          
          
                Student s = (Student)lit.previous();
                System.out.println(s.toString());
            }
    //     判断
            System.out.println(arrayList.contains(new Student("吴彦祖", 20)));
            System.out.println(arrayList.isEmpty());
    //        查找
            System.out.println(s1);
    
        }
    }
    
  • 重写equals 方法

        @Override
        public boolean equals(Object obj) {
          
          
            if (this == obj){
          
          
                return true;
            }
            if (this == null){
          
          
                return  false;
            }
            if (obj instanceof Student){
          
          
                Student s = (Student)obj;
    //            比较属性
                if (this.name.equals(s.getName())&&this.age==s.getAge()){
          
          
                    return true;
                }
            }
    //        不满足条件
            return false;
        }
    }
    

ArrayList 源码分析

  • 默认容量大小 : DEFAULT_CAPACITY = 10;

    • 如果没有向集合中添加任何元素,容量0
  • 存放元素的数组:elementData

  • 实际的元素个数:size

  • add() 添加元素

    • public boolean add(E e) {
              
              
          ensureCapacityInternal(size + 1);  // Increments modCount!!
          elementData[size++] = e;
          return true;
      }
      
          private static int calculateCapacity(Object[] elementData, int minCapacity) {
              
              
              if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
              
              
                  return Math.max(DEFAULT_CAPACITY, minCapacity);
              }
              return minCapacity;
          }
      
       private void ensureExplicitCapacity(int minCapacity) {
              
              
              modCount++;
      
              // overflow-conscious code
              if (minCapacity - elementData.length > 0)
                  grow(minCapacity);
          }
      
      private void grow(int minCapacity) {
              
              
              // overflow-conscious code
              int oldCapacity = elementData.length;
              int newCapacity = oldCapacity + (oldCapacity >> 1);
              if (newCapacity - minCapacity < 0)
                  newCapacity = minCapacity;
              if (newCapacity - MAX_ARRAY_SIZE > 0)
                  newCapacity = hugeCapacity(minCapacity);
              // minCapacity is usually close to size, so this is a win:
              elementData = Arrays.copyOf(elementData, newCapacity);
          }
      

Vector 使用

  • public class Demo01 {
          
          
        public static void main(String[] args) {
          
          
    //        创建集合
            Vector vector = new Vector();
    //        添加元素
            vector.add("草莓");
            vector.add("西瓜");
            vector.add("芒果");
            System.out.println("元素个数:"+vector.size());
    //        删除
    //        vector.remove(0);
    //        vector.remove("西瓜");
    //        vector.clear();
    //        System.out.println("元素个数:"+vector.size());
    //        遍历
    //        使用枚举器
            Enumeration en = vector.elements();
            while (en.hasMoreElements()){
          
          
                Object o = (String)en.nextElement();
                System.out.println(o);
            }
    //        判断
            System.out.println(vector.contains("西瓜"));
            System.out.println(vector.isEmpty());
    //        其他方法
    //        firsetElement、lastElement、ElementAt();
        }
    }
    

LinkedList 的使用

  • public class Demo01 {
          
          
        public static void main(String[] args) {
          
          
    //        创建集合
            LinkedList linkedList = new LinkedList<>();
    //        添加元素
            Student s1 = new Student("刘德华", 20);
            Student s2 = new Student("成龙", 20);
            Student s3 = new Student("吴彦祖", 20);
            linkedList.add(s1);
            linkedList.add(s2);
            linkedList.add(s3);
            System.out.println("元素个数:"+linkedList.size());
            System.out.println(linkedList.toString());
    //        删除
    //        linkedList.remove(new Student("成龙", 20));
    //        System.out.println("删除之后"+linkedList.size());
    //        linkedList.clear();
    //        遍历
    //        for遍历
            System.out.println("===================================");
            for (int i = 0;i<linkedList.size();i++){
          
          
                System.out.println(linkedList.get(i));
            }
    //        增强for
            System.out.println("===================================");
            for (Object object : linkedList) {
          
          
              Student s  = (Student) object;
                System.out.println(s.toString());
            }
    //        迭代器
            System.out.println("===================================");
            Iterator it = linkedList.iterator();
            while (it.hasNext()){
          
          
                Student s = (Student)it.next();
                System.out.println(s.toString());
            }
    //        列表迭代器
            System.out.println("===================================");
            ListIterator lit = linkedList.listIterator();
            while (lit.hasNext()){
          
          
                Student s = (Student)lit.next();
                System.out.println(s.toString());
            }
    
    //        判断
            System.out.println(linkedList.contains(s1));
            System.out.println(linkedList.isEmpty());
    //        获取
            System.out.println(linkedList.indexOf(s2));
    
    
        }
    }
    

LinkedList 源码分析

  • int size : 集合的大小

  • Node first :链表的头节点

  • Node last : 链表的尾节点

  • void linkLast(E e) {
          
          
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }
    
  • private static class Node<E> {
          
          
        E item;
        Node<E> next;
        Node<E> prev;
    
        Node(Node<E> prev, E element, Node<E> next) {
          
          
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }
    

ArrayList 和 LinkedList 区别

  • 不同的结构实现方式

在这里插入图片描述

泛型概述

  • Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递
  • 常见形式有泛型类、泛型接口、泛型方法
  • 语法:
    • <T,…> T成为类型占位符,表示一种引用类型

泛型类

  • package com.gather.MyGeneric;
    
    /**
     * 泛型类
     * 语法:类名<T>
     * T 是类型占位符,表示一种引用类型 ,如果编写多个使用逗号隔开
     */
    public class MyGeneric<T> {
          
          
    //    使用泛型T
    //    创建变量
        T t;
    //    作为方法的参数
        public void show(T t){
          
          
            System.out.println(t);
    
        }
    //    泛型作为方法的返回值
        public T getT(){
          
          
            return t;
        }
    
    }
    
  • package com.gather.MyGeneric;
    
    public class TestGeneric {
          
          
        public static void main(String[] args) {
          
          
    //        使用泛型类创建对象
    //        注意:1.泛型只能是引用类型
    //               2.不同泛型类型对象之间不能互相复制
            MyGeneric<String> myGeneric = new MyGeneric<String>();
            myGeneric.t = "hello";
            myGeneric.show("大家好");
            String string = myGeneric.getT();
    
            MyGeneric<Integer> myGeneric2 = new MyGeneric<Integer>();
            myGeneric2.t = 100;
            myGeneric2.show(200);
            Integer integer = myGeneric2.getT();
    
        }
    }
    

泛型接口

  • package com.gather.MyGeneric;
    /*
    泛型接口
    语法: 接口名<T>;
    注意:不能泛型静态常量
     */
    
    public interface MyInterface <T> {
          
          
        String name = "张三";
    
        T server(T t);
    }
    
  • package com.gather.MyGeneric;
    
    public class MyInterfaceImpl implements MyInterface<String> {
          
          
        @Override
        public String server(String t) {
          
          
            System.out.println(t);
            return t;
    
        }
    }
    
  • package com.gather.MyGeneric;
    
    public class MyInterfaceImpl2<T> implements MyInterface<T> {
          
          
        @Override
        public T server(T t) {
          
          
            System.out.println(t);
            return t;
        }
    }
    
  • MyInterfaceImpl impl = new MyInterfaceImpl();
    impl.server("xxxxxxxxxxxx");
    
    MyInterfaceImpl2<Integer> impl2 = new MyInterfaceImpl2<>();
    impl2.server(1000);
    

泛型方法

  • package com.gather.MyGeneric;
    /**
     * 泛型方法
     * 语法:<T> 返回值类型
     */
    
    public class MyGenericMethod {
          
          
    //    泛型方法
        public <T> T show(T t){
          
          
            System.out.println("泛型方法"+t);
            return t;
        }
        
    }
    
  • //        泛型方法
            MyGenericMethod myGenericMethod = new MyGenericMethod();
            myGenericMethod.show("张世杰");
            myGenericMethod.show(200);
            myGenericMethod.show(3.1415926);
    

泛型好处

  • 好处:
    1. 提高代码的重用性
    2. 防止类型转化异常,提高代码的安全性

泛型集合

  • 概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致

  • 特点:

    • 编译时即可检查,而非运行时抛出异常
    • 访问时,不必类型转换(拆箱)
    • 不同泛型之间引用不能相互赋值,泛型不存在多态
  • package com.gather.MyGeneric;
    
    import com.kind.chapter_1.Student;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    
    public class Demo {
          
          
        public static void main(String[] args) {
          
          
            ArrayList<String> arrayList = new ArrayList<String>();
            arrayList.add("xxx");
            arrayList.add("yyy");
    //        arrayList.add(10);
    //        arrayList.add(20);
    
            for (String string : arrayList) {
          
          
                System.out.println(string);
    
            }
    
            ArrayList<Student> arrayList2 = new ArrayList<Student>();
            Student s1 = new Student("刘德华", 20);
            Student s2 = new Student("成龙", 20);
            Student s3 = new Student("吴彦祖", 20);
            arrayList2.add(s1);
            arrayList2.add(s2);
            arrayList2.add(s3);
    
            Iterator<Student> it = arrayList2.iterator();
            while(it.hasNext()){
          
          
                Student s = it.next();
                System.out.println(s.toString());
            }
        }
    

猜你喜欢

转载自blog.csdn.net/xiaoxiaobaie/article/details/121463254