溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java集合原理實例分析

發(fā)布時間:2022-05-19 11:48:58 來源:億速云 閱讀:143 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容主要講解“java集合原理實例分析”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“java集合原理實例分析”吧!

一、概述

集合是一種長度可變,存儲數(shù)據(jù)的數(shù)據(jù)結構多樣,存儲對象多樣的一種數(shù)據(jù)容器。Java中集合可分為:List集合、Set集合、HashMap集合,等。

Java集合體系結構:

java集合原理實例分析

二、collection

collection是Java中所有值存儲集合的頂級接口,因此它的所有直接或者間接實現(xiàn)類都有它的非私有方法,我們可以從它的方法開始了解這個體系的功能實現(xiàn)。

 boolean add(E e) 
          確保此 collection 包含指定的元素。 
 boolean addAll(Collection<? extends E> c) 
          將指定 collection 中的所有元素都添加到此 collection 中。 
 void clear() 
          移除此 collection 中的所有元素。 
 boolean contains(Object o) 
          如果此 collection 包含指定的元素,則返回 true。 
 boolean containsAll(Collection<?> c) 
          如果此 collection 包含指定 collection 中的所有元素,則返回 true。 
 boolean equals(Object o) 
          比較此 collection 與指定對象是否相等。 
 int hashCode() 
          返回此 collection 的哈希碼值。 
 boolean isEmpty() 
          如果此 collection 不包含元素,則返回 true。 
 Iterator<E> iterator() 
          返回在此 collection 的元素上進行迭代的迭代器。 
 boolean remove(Object o) 
          從此 collection 中移除指定元素的單個實例,如果存在的話)。 
 boolean removeAll(Collection<?> c) 
          移除此 collection 中那些也包含在指定 collection 中的所有元素。 
 boolean retainAll(Collection<?> c) 
          僅保留此 collection 中那些也包含在指定 collection 的元素。 
 int size() 
          返回此 collection 中的元素數(shù)。 
 Object[] toArray() 
          返回包含此 collection 中所有元素的數(shù)組。 
<T> T[] 
 toArray(T[] a) 
          返回包含此 collection 中所有元素的數(shù)組;返回數(shù)組的運行時類型與指定數(shù)組的運行時類型相同。

1、List

List,是單列集合,存儲的是一組插入有序的數(shù)據(jù),并且數(shù)據(jù)可以重復。

List集合

  • LinkedList

  • ArrayList

1)ArrayList

示例:

public class CollectionTest {
    public static void main(String[] args) {
        List list = new ArrayList();
        //添加元素,boolean add(E e) 確保此 collection 包含指定的元素
        list.add("張三");
        list.add(1);
        list.add('A');
        System.out.println(list);//[張三, 1, A]
        //boolean addAll(Collection<? extends E> c)
        //          將指定 collection 中的所有元素都添加到此 collection 中
        List list1 = new ArrayList();
        list.add("java");
        list.add("MySQL");
        list.addAll(list1);
        System.out.println(list);//[張三, 1, A, java, MySQL]
        //boolean contains(Object o)
        //          如果此 collection 包含指定的元素,則返回 true。
        System.out.println(list.contains("java"));//true
        //boolean remove(Object o)
        //          從此 collection 中移除指定元素的單個實例,如果存在的話)。
        System.out.println(list.remove("java"));//true
        // int size()
        //          返回此 collection 中的元素數(shù)。
        System.out.println(list.size());//4
        //set(int index, E element)
        //          用指定的元素替代此列表中指定位置上的元素。
        //并返回被修改的值
        System.out.println(list.set(1, "李四"));
        //get(int index) 
        //          返回此列表中指定位置上的元素。
        System.out.println(list.get(1));
        // Iterator<E> iterator()
        //          返回在此 collection 的元素上進行迭代的迭代器。
        //集合的遍歷
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

說明:ArrayList底層是使用數(shù)組的形式創(chuàng)建集合的,因此基于數(shù)組的特性,此集合對數(shù)據(jù)的查找很快速,但是在刪除或移動大量數(shù)據(jù)操作上會顯得緩慢。它適合用于快速查找,但不適合做刪除多的操作。

2)LinkedList

LinkedList:雙向鏈表,內(nèi)部沒有聲明數(shù)組,而是定義了Node類型的first 和last,用于記錄首末元素。同時,定義內(nèi)部類Node,作為LinkedList中 保存數(shù)據(jù)的基本結構。Node除了保存數(shù)據(jù),還定義了兩個變量:

  • prev變量記錄前一個元素的位置

  • next變量記錄下一個元素的位置

特點:

  • 數(shù)據(jù)有序

  • 底層結構為鏈表

ArrayList比較:

  • LinkedList的添加元素速度比ArrayList快;

  • LinkedList的查詢速度比ArrayList慢;

  • 底層數(shù)據(jù)結構不同:LinkedList用的是鏈表結構,而ArrayList底層使用 的是數(shù)組結構;

說明:LinkedList一般用于添加頻繁的操作,ArrayList一般用于頻繁查詢 的操作。

示例:

public class Stack {
    private LinkedList data = null;
    public Stack(){
        data = new LinkedList();
    }
    // 添加元素
    public boolean push(Object element) {
        data.addFirst(element);
        return true;
    }
    // 獲取元素
    public Object pop() {
        return data.pollFirst();
    }
    // 判斷集合是否為空
    public boolean isEmpty() {
        return data.isEmpty();
    }
    // 迭代元素
    public void list() {
        Iterator it = data.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}
public class MyStack {
    public static void main(String[] args) {
        Stack stack = new Stack();
        stack.push("張三");
        stack.push("李四");
        stack.push("王五");
        stack.list();
        System.out.println("-------------");
        Object pop = stack.pop();
        System.out.println(pop);
    }
}

2、set

1)HashSet

HashSet 是 Set 接口的典型實現(xiàn),大多數(shù)時候使用 Set 集合時都使用 這個實現(xiàn)類。

  • HashSet 按 Hash 算法來存儲集合中的元素,因此具有很好的存取、 查找、刪除性能。

    • HashSet 具有以下特點:不能保證元素的排列順序

    • HashSet 不是線程安全的

    • 集合元素可以是 null

    • 不能添加重復元素

  • HashSet 集合判斷兩個元素相等的標準:兩個對象通過 hashCode() 方法比較相等,并且兩個對象的 equals() 方法返回值也相等。

  • 對于存放在Set容器中的對象,對應的類一定要重寫equals()和 hashCode(Object obj)方法,以實現(xiàn)對象相等規(guī)則。即:“相等的對象必須具有相等的散列碼”。

示例:

 public static void main(String[] args) {
        Set set = new HashSet();
        // 添加
        // boolean add(E e) :把指定的元素添加到集合中
        set.add("hello");
        set.add("world");
        set.add("world");
        set.add(null);
        System.out.println(set);
        // 注:Set集合中元素是無序,并且不能重復
        // boolean addAll(Collection<? extends E> c) :把指定的集合添加到集合中
        Set set1 = new HashSet();
        set1.add("aaa");
        set1.add("linux");
        ;
        set.addAll(set1);
        System.out.println(set);
        // boolean remove(Object o) :從集合中刪除指定元素
        set.remove("hello");
        System.out.println(set);
        // boolean removeAll(Collection<?> c) :從集合中刪除指定集合中的所有元素
        set1.add("aaa");
        set1.add("linux");
        set.removeAll(set1);
        System.out.println(set);
        // void clear() :清空集合中所有元素
        set.clear();
        System.out.println(set);
        // int size() :獲取集合的元素個數(shù)
        int size = set.size();
        System.out.println(size);
        // boolean contains(Object o) :判斷集合中是否包含指定元素,包含為true,否則為false;
        System.out.println(set.contains("aaa"));

        // boolean isEmpty() :判斷集合是否為空
        System.out.println(set.isEmpty());
    }

說明:在HashSet添加元素時,會首先比較兩個元素的hashCode值是不相等,如 果不相等則直接添加;如果相等再判斷兩個元素的equals的值是否相等, 如果相等則不添加,如果不相等則添加。

2)TreeSet

  • TreeSet和TreeMap采用紅黑樹的存儲結構

  • 特點:有序,查詢速度比List快

使用TreeSet集合是,對象必須具有可比較性。而要讓對象具有可比較性有 兩種方式:

第一種:實現(xiàn)Comparable接口,并重寫compareTo()方法:

第二種:寫一個比較器類,讓該類去實現(xiàn)Comparator接口,并重寫 comare()方法。

示例:

1.實體類
public class Student implements Comparable<Student>{
    private String name;
    private int age;
    private String sex;
    private int height;

    public Student() {
    }
    public Student(String name, int age, String sex, int height) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.height = height;
    }
    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 String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getHeight() {
        return height;
    }
    public void setHeight(int height) {
        this.height = height;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                height == student.height &&
                Objects.equals(name, student.name) &&
                Objects.equals(sex, student.sex);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name, age, sex, height);
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", height=" + height +
                '}';
    }

    @Override
    public int compareTo(Student stu) {
        if (stu.getAge() > this.getAge()){
            return 1;
        }
        if (stu.getAge() < this.getAge()){
            return -1;
        }
        return stu.getName().compareTo(this.getName());
    }
}
2.測試類:
public class TreeSetTest {
    public static void main(String[] args) {

        TreeSet treeSet = new TreeSet();
        Student student1 = new Student("張三", 20, "男", 165);
        Student student2 = new Student("李四", 21, "男", 170);
        Student student3 = new Student("王五", 19, "女", 160);
        Student student4 = new Student("趙六", 18, "女", 165);
        Student student5 = new Student("田七", 20, "男", 175);
        treeSet.add(student1);
        treeSet.add(student2);
        treeSet.add(student3);
        treeSet.add(student4);
        treeSet.add(student5);
        System.out.println(treeSet);
    }
}
3.實體類
public class Teacher {
    private String name;
    public Teacher(){}
    public Teacher(String name){
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                '}';
    }
}
4.測試類
public class TreeSetTest2 {
    public static void main(String[] args) {
        Teacher teacher1 = new Teacher("11");
        Teacher teacher2 = new Teacher("12");
        Teacher teacher3 = new Teacher("13");
        Teacher teacher4 = new Teacher("14");
        Teacher teacher5 = new Teacher("15");
        TreeSet treeSet1 = new TreeSet(new  Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return o1.hashCode() - o2.hashCode();
            }
        });
        treeSet1.add(teacher1);
        treeSet1.add(teacher2);
        treeSet1.add(teacher3);
        treeSet1.add(teacher4);
        treeSet1.add(teacher5);
        System.out.println(treeSet1);
    }
}

說明:HashSet去重是依靠hashCodeequals()方法,而TreeSet去重則 依靠的是比較器。

到此,相信大家對“java集合原理實例分析”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI