jgcs123

导航

 

 

1. Collection集合

1.1集合体系结构

  • 集合类的特点

    • 提供一种存储空间可变的存储模型,存储的数据容量可以随时发生改变

  • 集合类的体系图

 

1.2 Collection集合概述和基本使用

  • Collection集合概述

    • 是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素

    • JDK 不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现

  • Collection集合基本使用

public class CollectionDemo01 {
   public static void main(String[] args) {
       //创建Collection集合的对象
       Collection<String> c = new ArrayList<String>();

       //添加元素:boolean add(E e)
       c.add("hello");
       c.add("world");
       c.add("java");

       //输出集合对象
       System.out.println(c);

  }
}

 

1.3 Collection集合的常用方法

方法名说明
boolean add(E e) 添加元素
boolean remove(Object o) 从集合中移除指定的元素
void clear() 清空集合中的元素
boolean contains(Object o) 判断集合中是否存在指定的元素
boolean isEmpty() 判断集合是否为空
int size() 集合的长度,也就是集合中元素的个数

 

 

1.4 Collection集合的遍历

  • 迭代器的介绍

    • 迭代器,集合的专用遍历方式

    • Iterator iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到

    • 迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的

  • Collection集合的遍历

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/*
   Iterator:迭代器,集合的专用遍历方式
       Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
       迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的

   Iterator中的常用方法
       E next():返回迭代中的下一个元素
       boolean hasNext():如果迭代具有更多元素,则返回 true
*/
public class IteratorDemo {
   public static void main(String[] args) {
       //创建集合对象
       Collection<String> c = new ArrayList<String>();

       //添加元素
       c.add("hello");
       c.add("world");
       c.add("java");

       //Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
       Iterator<String> it = c.iterator();
       /*
           public Iterator<E> iterator() {
               return new Itr();
           }

           private class Itr implements Iterator<E> {
               ...
           }
        */

       //E next():返回迭代中的下一个元素
       /*
       System.out.println(it.next());
       System.out.println(it.next());
       System.out.println(it.next());
       System.out.println(it.next()); //NoSuchElementException:表示被请求的元素不存在
       */

       //boolean hasNext():如果迭代具有更多元素,则返回 true
       /*
       if(it.hasNext()) {
           System.out.println(it.next());
       }

       if(it.hasNext()) {
           System.out.println(it.next());
       }

       if(it.hasNext()) {
           System.out.println(it.next());
       }

       if(it.hasNext()) {
           System.out.println(it.next());
       }
       */

       //用while循环改进判断
       while (it.hasNext()) {
//           System.out.println(it.next());
           String s = it.next();
           System.out.println(s);
      }

  }
}

 

1.5 集合使用步骤图解

  • 使用步骤

 

 

1.6 集合的案例-Collection集合存储学生对象并遍历

  • 案例需求

    • 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

  • 代码实现

    • 学生类

      public class Student {
         private String name;
         private int age;

         public Student() {
        }

         public Student(String name, int age) {
             this.name = name;
             this.age = age;
        }

         public String getName() {
             return name;
        }

         public void setName(String name) {
             this.name = name;
        }

         public int getAge() {
             return age;
        }

         public void setAge(int age) {
             this.age = age;
         @Override
         public String toString() {
             return "Student{" +
                     "name='" + name + '\'' +
                     ", age=" + age +
                     '}';
        }
      }
    • 测试类

      import java.util.ArrayList;
      import java.util.Collection;
      import java.util.Iterator;

      /*
         需求:
             创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

         思路:
             1:定义学生类
             2:创建Collection集合对象
             3:创建学生对象
             4:把学生添加到集合
             5:遍历集合(迭代器方式)
      */
      public class CollectionDemo {
         public static void main(String[] args) {
             //创建Collection集合对象
             Collection<Student> c = new ArrayList<Student>();

             //创建学生对象
             Student s1 = new Student("冬冬", 23);
             Student s2 = new Student("栗子", 23);
             Student s3 = new Student("三号", 24);

             //把学生添加到集合
             c.add(s1);
             c.add(s2);
             c.add(s3);

             //遍历集合(迭代器方式)
             Iterator<Student> it = c.iterator();

             while (it.hasNext()) {
                 Student s = it.next();
                 System.out.println(s.toString());
            }

        }
      }

 

 

2. List集合

2.1 List集合概述和特点

  • List集合概述

    • 有序集合(也称为序列),用户可以精确控制列表中每个元素的插入位置。用户可以通过整数索引访问元 素,并搜索列表中的元素

    • 与Set集合不同,列表通常允许重复的元素

  • List集合特点

    • 有索引

    • 可以存储重复元素

    • 元素存取有序

 

2.2 List集合的特有方法

方法名描述
void add(int index,E element) 在此集合中的指定位置插入指定的元素
E remove(int index) 在此集合中的指定位置插入指定的元素
E set(int index,E element) 修改指定索引处的元素,返回被修改的元素
E get(int index) 返回指定索引处的元素

 

2.3 集合的案例-List集合存储学生对象并遍历

  • 案例需求

    • 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

  • 代码实现

  • 学生类

    public class Student {
       private String name;
       private int age;

       public Student() {
      }

       @Override
       public String toString() {
           return "学生信息{" +
                   "姓名='" + name + '\'' +
                   ", 年龄=" + age +
                   '}';
      }

       public Student(String name, int age) {


           this.name = name;
           this.age = age;
      }

       public String getName() {
           return name;
      }

       public void setName(String name) {
           this.name = name;
      }

       public int getAge() {
           return age;
      }

       public void setAge(int age) {
           this.age = age;
      }
    }
    • 测试类

public class ListDemo {
   public static void main(String[] args) {
       //创建List集合对象
       ArrayList<Student> list = new ArrayList<>();
       Student s1 = new Student("冬冬", 23);
       Student s2 = new Student("栗子", 23);
       Student s3 = new Student("三号", 24);

       list.add(s1);
       list.add(s2);
       list.add(s3);

       Iterator<Student> it = list.iterator();
       while (it.hasNext()){
           Student s = it.next();
           System.out.println(s.toString());
      }

       System.out.println("--------");

       //for循环方式
       for(int i=0; i<list.size(); i++) {
           Student s = list.get(i);
           System.out.println(s.getName() + "," + s.getAge());
      }

  }
}

 

 

2.4 并发修改异常

  • 出现的原因

    • 迭代器遍历的过程中,通过集合对象修改了集合中的元素,造成了迭代器获取元素中判断预期修改值和实际 修改值不一致,则会出现:ConcurrentModificationException

  • 解决的方案

    • 用for循环遍历,然后用集合对象做对应的操作即可

  • 示例代码

 

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/*
   需求:
       我有一个集合:List<String> list = new ArrayList<String>();
       里面有三个元素:list.add("hello");list.add("world");list.add("java");
       遍历集合,得到每一个元素,看有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现

   ConcurrentModificationException:当不允许这样的修改时,可以通过检测到对象的并发修改的方法来抛出此异常
*/
public class ListDemo {
   public static void main(String[] args) {
       //创建集合对象
       List<String> list = new ArrayList<String>();

       //添加元素
       list.add("hello");
       list.add("world");
       list.add("java");

       //遍历集合,得到每一个元素,看有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现
//       Iterator<String> it = list.iterator();
//       while (it.hasNext()) {
//           String s = it.next();
//           if(s.equals("world")) {
//               list.add("javaee");
//           }
//       }

       for(int i=0; i<list.size(); i++) {
           String s = list.get(i);
           if(s.equals("world")) {
               list.add("javaee");
          }
      }

       //输出集合对象
       System.out.println(list);
  }
}
public interface List<E> {
  Iterator<E> iterator();
  boolean add(E e);
}

public abstract class AbstractList<E> {
  protected int modCount = 0;
}

public class ArrayList<E> extends AbstractList<E> implements List<E> {

  public E get(int index) {
      Objects.checkIndex(index, size);
      return elementData(index);
  }

  public boolean add(E e) {
      modCount++;
      add(e, elementData, size);
      return true;
  }

  public Iterator<E> iterator() {
      return new Itr();
  }

  private class Itr implements Iterator<E> {
      int expectedModCount = modCount;
      /*
          modCount:实际修改集合的次数
          expectedModCount:预期修改集合的次数
      */

      public E next() {
          checkForComodification();
          int i = cursor;
          if (i >= size)
              throw new NoSuchElementException();
          Object[] elementData = ArrayList.this.elementData;
          if (i >= elementData.length)
              throw new ConcurrentModificationException();
          cursor = i + 1;
          return (E) elementData[lastRet = i];
      }

      final void checkForComodification() {
          if (modCount != expectedModCount)
              throw new ConcurrentModificationException();
      }
  }

}

2.5 ListIterator列表迭代器

  • ListIterator介绍

    • 通过List集合的listIterator()方法得到,所以说它是List集合特有的迭代器

    • 用于允许程序员沿任一方向遍历的列表迭代器,在迭代期间修改列表,并获取列表中迭代器的当前位置

  • 示例代码

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/*
   ListIterator:列表迭代器
       通过List集合的listIterator()方法得到,所以说它是List集合特有的迭代器
       用于允许程序员沿任一方向遍历列表的列表的迭代器,在迭代期间修改列表,并获取列表中迭代器的当前位置

   ListIterator中的常用方法
       E next():返回迭代中的下一个元素
       boolean hasNext():如果迭代具有更多元素,则返回 true
       E previous():返回列表中的上一个元素
       boolean hasPrevious():如果此列表迭代器在相反方向遍历列表时具有更多元素,则返回 true
       void add(E e):将指定的元素插入列表
*/
public class ListIteratorDemo {
   public static void main(String[] args) {
       //创建集合对象
       List<String> list = new ArrayList<String>();

       //添加元素
       list.add("hello");
       list.add("world");
       list.add("java");

       //获取列表迭代器
       ListIterator<String> lit = list.listIterator();
       while (lit.hasNext()) {
           String s = lit.next();
           if(s.equals("world")) {
               lit.add("javaee");
          }
      }

       System.out.println(list);

  }
}

2.6 增强for循环

 

增强for:简化数组和Collection集合的遍历

  • 实现Iterable接口的类允许其对象成为增强型for语句的目标

  • 它是JDK5之后出现的,其内部原理是一个Iterator迭代器

  • 格式

for(元素数据类型 变量名 : 数组/集合对象名) {
循环体;
}
  • 示例代码

public class ForDemo {
   public static void main(String[] args) {
       int[] arr = {1,2,3,4,5};
       for (int i :arr){
           System.out.print(i);
      }
       System.out.println("--------");

       String[] strArray = {"hello","world","java"};
       for(String s : strArray) {
           System.out.println(s);
      }
       System.out.println("--------");

       List<String> list = new ArrayList<String>();
       list.add("hello");
       list.add("world");
       list.add("java");

       for(String s : list) {
           System.out.println(s);
      }
       System.out.println("--------");
  }
}

 

2.7 集合的案例-List集合存储学生对象三种方式遍历

 

  • 案例需求

    • 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

  • 代码实现

    • 学生类

      public class Student {
         private String name;
         private int age;

         public Student() {
        }

         public Student(String name, int age) {


             this.name = name;
             this.age = age;
        }

         public String getName() {
             return name;
        }

         public void setName(String name) {
             this.name = name;
        }

         public int getAge() {
             return age;
        }

         @Override
         public String toString() {
             return "学生信息{" +
                     "名字='" + name + '\'' +
                     ", 年龄=" + age +
                     '}';
        }

         public void setAge(int age) {
             this.age = age;
        }
      }
    • 测试类

      /*
         思路:
             1:定义学生类
             2:创建List集合对象
             3:创建学生对象
             4:把学生添加到集合
             5:遍历集合
                 迭代器:集合特有的遍历方式
                 普通for:带有索引的遍历方式
                 增强for:最方便的遍历方式
      */
      public class ListDemo {
         public static void main(String[] args) {
             //创建List集合对象
             List<Student> list = new ArrayList<Student>();

             //创建学生对象
             Student s1 = new Student("冬冬", 23);
             Student s2 = new Student("栗子", 23);
             Student s3 = new Student("三号", 33);

             //把学生添加到集合
             list.add(s1);
             list.add(s2);
             list.add(s3);

             //迭代器:集合特有的遍历方式
             Iterator<Student> it =list.iterator();
             while (it.hasNext()){
                Student s = it.next();
                 System.out.println(s.toString());
            }
             System.out.println("--------");

             //普通for:带有索引的遍历方式
             for (int i = 0; i<list.size();i++){
                 Student s = list.get(i);
                 System.out.println(s.toString());
            }
             System.out.println("--------");

             //增强for:最方便的遍历方式
             for (Student s :list){
                 System.out.println(s.toString());
            }
        }
      }

 

 

3. 数据结构

数据结构是计算机存储、组织数据的方式。是指相互之间存在一种或多种特定关系的数据元素的集合

通常情况下,精心选择的数据结构可以带来更高的运行或者存储效率。

3.1 常见数据结构之栈和队列

  • 栈结构

    先进后出

  • 队列结构

    先进先出

3.2 常见数据结构之数组和链表

  • 数组是一种查询快,增删慢的模型

    • 查询数据通过索引定位,查询任意数据耗时相同,查询效率高

    • 删除数据时,要将原始数据删除,同时后面每个数据前移,删除效率低

    • 添加数据时,添加位置后的每个数据后移,再添加元素,添加效率极低

数组结构 查询快、增删慢

 

链表黑马程序员全套Java教程Java基础入门教程,零基础小白自学Java必备教程哔哩哔哩_bilibili

 

链表是一种增删快的模型(对比数组)

链表是一种查询慢的模型(对比数组)

 

 

4. List集合的实现类

4.1 List集合子类的特点

  • ArrayList集合

    • 底层是数组结构实现,查询快、增删慢

  • LinkedList集合

    • 底层是链表结构实现,查询慢、增删快

 

4.2 集合的案例-ArrayList集合存储学生对象三种方式遍历

  • 案例需求

    • 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

  • 代码实现

    • 学生类

      public class Student {
         private String name;
         private int age;

         public Student() {
        }

         public Student(String name, int age) {


             this.name = name;
             this.age = age;
        }

         public String getName() {
             return name;
        }

         public void setName(String name) {
             this.name = name;
        }

         public int getAge() {
             return age;
        }

         @Override
         public String toString() {
             return "学生信息{" +
                     "学生姓名='" + name + '\'' +
                     ", 学生年龄=" + age +
                     '}';
        }

         public void setAge(int age) {
             this.age = age;
        }
      }
    • 测试类

      /*
         思路:
             1:定义学生类
             2:创建ArrayList集合对象
             3:创建学生对象
             4:把学生添加到集合
             5:遍历集合
                 迭代器:集合特有的遍历方式
                 普通for:带有索引的遍历方式
                 增强for:最方便的遍历方式
      */
      public class ArrayListDemo {
         public static void main(String[] args) {
             //创建ArrayList集合对象
             ArrayList<Student> array = new ArrayList<Student>();

             //创建学生对象
             Student s1 = new Student("冬冬", 23);
             Student s2 = new Student("栗子", 23);
             Student s3 = new Student("三号", 33);

             //把学生添加到集合
             array.add(s1);
             array.add(s2);
             array.add(s3);

             //迭代器:集合特有的遍历方式
             Iterator<Student> it = array.iterator();
             while (it.hasNext()) {
                 Student s = it.next();
                 System.out.println(s.toString());
            }
             System.out.println("--------");

             //普通for:带有索引的遍历方式
             for (int i = 0; i < array.size(); i++) {
                 Student s = array.get(i);
                 System.out.println(s.toString());
            }
             System.out.println("--------");

             //增强for:最方便的遍历方式
             for (Student s : array) {
                 System.out.println(s.toString());
            }
        }
      }

 

4.3 LinkedList集合的特有功能

  • 特有方法

方法名说明
public void addFirst(E e) 在该列表开头插入指定的元素
public void addLast(E e) 将指定的元素追加到此列表的末尾
public E getFirst() 返回此列表中的第一个元素
public E getLast() 返回此列表中的最后一个元素
public E removeFirst() 从此列表中删除并返回第一个元素
public E removeLast() 从此列表中删除并返回最后一个元素
posted on 2021-06-26 13:52  Dongdong98  阅读(39)  评论(0)    收藏  举报