java 集合框架

java 集合框架

集合框架的介紹

我們在超市買東西的時候,如果沒有購物車是不是會很麻煩呢?Java 中集合類是一種工具類,就是像購物車一樣的容器,存儲任意數(shù)量的具有共同屬性的對象。

我們?yōu)槭裁匆眉夏??一個類的內(nèi)部有許多相同類型的屬性,并且他們的作用與意義是一樣的,我們最好用一個類似容器的東西去盛放他們,在類的內(nèi)部就變得井然有序。所以集合便是在類的內(nèi)部,對數(shù)據(jù)進行組織的作用。這樣我們便可以簡單而快速地搜索大量的條目。有的集合接口,提供了一系列排列有序的元素,并且可以在序列中快速地插入或者刪除有關(guān)元素。還有一些集合接口,提供了映射關(guān)系,可以通過關(guān)鍵字(key)去快速查找到對應(yīng)的唯一對象,而這個關(guān)鍵字可以是任意類型。

集合框架是為表示和操作集合而規(guī)定的一種統(tǒng)一的標準的體系結(jié)構(gòu)。任何集合框架都包含三大內(nèi)容:對外的接口、接口的實現(xiàn)和對集合運算的算法。

Collection 接口

因為集合框架中的很多類功能是相似的,所以我們用接口來規(guī)范類。

Collection接口是java集合框架里的一個根接口。他也是List、Set和Queue 接口的父接口。Collection接口中定義了可用于操作List、Set和Queue的方法--增刪改查

方法 返回值 說明
add(E e) boolean 向collection的尾部追加指定的元素(可選操作)
addAll(Collection<? extend E> c) boolean 將指定collection 中的所有元素都添加此collection中(可選操作)
clear() void 移除此collection中的所有元素(可選操作)
contains(Object o) boolean 如果此collection包含指定元素,則返回true
containsAll(Collection<?> c) boolean 如果此collection包含指定collection的所有元素,則返回true
equals(Object o) boolean 比較此collection與指定對象是否相等
hashCode() int 返回此collection的哈希碼值
isEmpty() boolean 如果此collection不包含元素 則返回true
iterator() Iterator<E> 返回在此collection的元素上進行迭代的迭代器
remove(Object o) boolean 移除此collection中出現(xiàn)的首個指定元素(可選操作)
removeAll(Collection<?> c) boolean 移除此 collection 中那些也包含在指定 collection 中的所有元素(可選操作)
retainAll(Collection<?> c) boolean 僅保留此 collection 中那些也包含在指定 collection 的元素(可選操作)
size() int 返回此collection中的元素數(shù)
toArray() Object[] 返回包含此collection中所有元素的數(shù)組
toArray(T[] a) <T> T[] 返回包含此 collection 中所有元素的數(shù)組;返回數(shù)組的運行時類型與指定數(shù)組的運行時類型相同

List 接口 與 ArrayList 類

List是一個接口,不能實例化,需要一個具體類來實現(xiàn)實例化。List集合中的對象按照一定的順序排放,里面的內(nèi)容可以重復(fù)。List接口實現(xiàn)的類有:ArrayList(實現(xiàn)動態(tài)數(shù)組),Vector(實現(xiàn)動態(tài)數(shù)組), LinkedList(實現(xiàn)鏈表),Stack(實現(xiàn)堆棧).

List在Collection 基礎(chǔ)上的方法

方法 返回值 說明
add(int index, E element) void 在列表的指定位置插入指定元素(可選操作)
addAll(int index, Collection<? extends E> c) boolean 將指定 collection 中的所有元素都插入到列表中的指定位置(可選操作)
get(int index) E 返回列表中指定位置的元素
indexOf(Object o) int 返回此列表中第一次出現(xiàn)的指定元素的索引;如果此列表不包含該元素,則返回 -1
lastIndexOf(Object o) int 返回此列表中最后出現(xiàn)的指定元素的索引;如果列表不包含此元素,則返回 -1
listIterator() ListIterator<E> 返回此列表元素的列表迭代器(按適當順序)
listIterator(int index) ListIterator<E> 返回此列表元素的列表迭代器(按適當順序),從列表的指定位置開始
remove(int index) E 移除列表中指定位置的元素(可選操作)
set(int index, E element) E 用指定元素替換列表中指定位置的元素(可選操作)
subList(int fromIndex, int toIndex) List<E> 返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之間的部分視圖

今天我們主要來學習  java.util.ArrayList,ArrayList  類實現(xiàn)一個可增長的動態(tài)數(shù)組,它可以存儲不同類型的對象,而數(shù)組則只能存放特定數(shù)據(jù)類型的值。

我們通過實際的例子來學習 ArrayList 吧!學校的教務(wù)系統(tǒng)會對學生進行統(tǒng)一的管理,每一個學生都會有一個學號和學生姓名,我們在維護整個系統(tǒng)的時候,大多數(shù)操作是對學生的添加、插入、刪除、修改等操作。

先創(chuàng)建一個學生類:

/*
 * 學生類
 */

public class Student {
    public String id;
    public String name;
    public Student(String id, String name){
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

管理學生類:

import java.util.*;

public class ListTest {

    //集合后面的<>代表泛型的意思
    //泛型是規(guī)定了集合元素的類型
    //我們以后會詳細講到
    /**
     * 用于存放學生的 List
     */
    public List<Student> students;

    public ListTest() {
        this.students = new ArrayList<Student>();
    }

    /**
     * 用于往 students 中添加學生
     */
    public void testAdd() {
        // 創(chuàng)建一個學生對象,并通過調(diào)用 add 方法,添加到學生管理 List 中
        Student st1 = new Student("1", "張三");
        students.add(st1);

        // 取出 List 中的 Student 對象
        Student temp = students.get(0);
        System.out.println("添加了學生:" + temp.id + ":" + temp.name);

        Student st2 = new Student("2", "李四");
        students.add(0, st2);
        Student temp2 = students.get(0);
        System.out.println("添加了學生:" + temp2.id + ":" + temp2.name);

        // 對象數(shù)組的形式添加
        Student[] student = {new Student("3", "王五"), new Student("4", "馬六")};

        // Arrays 類包含用來操作數(shù)組(比如排序和搜索)的各種方法,asList() 方法用來返回一個受指定數(shù)組支持的固定大小的列表
        students.addAll(Arrays.asList(student));
        Student temp3 = students.get(2);
        Student temp4 = students.get(3);
        System.out.println("添加了學生:" + temp3.id + ":" + temp3.name);
        System.out.println("添加了學生:" + temp4.id + ":" + temp4.name);
        Student[] student2 = {new Student("5", "周七"), new Student("6", "趙八")};
        students.addAll(2, Arrays.asList(student2));
        Student temp5 = students.get(2);
        Student temp6 = students.get(3);
        System.out.println("添加了學生:" + temp5.id + ":" + temp5.name);
        System.out.println("添加了學生:" + temp6.id + ":" + temp6.name);
    }

    /**
     * 取得 List 中的元素的方法
     */
    public void testGet() {
        int size = students.size();
        for (int i = 0; i < size; i++) {
            Student st = students.get(i);
            System.out.println("學生:" + st.id + ":" + st.name);

        }
    }

    /**
     * 通過迭代器來遍歷
     */
    // 迭代器的工作是遍歷并選擇序列中的對象,Java 中 Iterator 只能單向移動
    public void testIterator() {
        // 通過集合的 iterator 方法,取得迭代器實例
        Iterator<Student> it = students.iterator();
        System.out.println("有如下學生(通過迭代器訪問):");
        while (it.hasNext()) {

            Student st = it.next();
            System.out.println("學生" + st.id + ":" + st.name);
        }
    }

    /**
     * 通過 for each 方法訪問集合元素
     *
     */
    public void testForEach() {
        System.out.println("有如下學生(通過 for each):");
        for (Student obj : students) {
            Student st = obj;
            System.out.println("學生:" + st.id + ":" + st.name);
        }
        //使用 java8 Steam 將學生排序后輸出
        students.stream()//創(chuàng)建 Stream
                //通過學生 id 排序
                .sorted(Comparator.comparing(x -> x.id))
                //輸出
                .forEach(System.out::println);
    }

    /**
     * 修改 List 中的元素
     *
     */
    public void testModify() {
        students.set(4, new Student("3", "吳酒"));
    }

    /**
     * 刪除 List 中的元素
     *
     */
    public void testRemove() {
        Student st = students.get(4);
        System.out.println("我是學生:" + st.id + ":" + st.name + ",我即將被刪除");
        students.remove(st);
        System.out.println("成功刪除學生!");
        testForEach();

    }

    public static void main(String[] args) {
        ListTest lt = new ListTest();
        lt.testAdd();
        lt.testGet();
        lt.testIterator();
        lt.testModify();
        lt.testForEach();
        lt.testRemove();

    }
}

上面的代碼中,用到了 Arrays 類, Arrays 包含用來操作數(shù)組(比如排序和搜索)的各種方法,asList() 方法用來返回一個受指定數(shù)組支持的固定大小的列表。

List 有兩種基本的類型,除了ArrayList外,還有LinkedList,LinkedList類用于創(chuàng)建鏈表數(shù)據(jù)結(jié)構(gòu),兩者的對比如下:

  • ArrayList:它擅長于隨機訪問元素,但是插入和移除元素很慢
  • LinkedList: 它通過代價較低的在List中進行插入和刪除操作,提供了優(yōu)化的順序訪問,它在隨機訪問方面相對較慢,但是它的特性集較ArrayList更大。

Set接口 和 HashSet 類

Set接口也是Collection接口的子接口,它有一個很重要也是很常用的實現(xiàn)類————HashSet,Set是元素無序并且不包含重復(fù)元素的collection(List可以重復(fù)),被稱為集。

HashSet由哈希表(實際上是一個HashMap實例)支持。它不保證set的迭代順序;特別是它不保證該順序恒久不變。

接下來我們同樣通過代碼的形式來詳細看一看吧!

在上面我們實現(xiàn)了學生的管理,現(xiàn)在學生要做項目,每一個項目有一個組長,由組長來組織組員,我們便來實現(xiàn)項目組的管理

因為項目組的組長由一個老師擔任,首先我們來創(chuàng)建一個 PD 類

import java.util.HashSet;
import java.util.Set;
/*
 * 項目組長類
 */
public class PD {

    public String id;
    public String name;
    //集合后面的<>代表泛型的意思
    //泛型是規(guī)定了集合元素的類型
    //我們以后會詳細講到
    public Set<Student> students;
    public PD(String id, String name){
        this.id = id;
        this.name = name;
        this.students = new HashSet<Student>();
    }
}

接下來我們便創(chuàng)建一個 SetTest 類,用來管理項目成員

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class SetTest {

    public List<Student> students;

    public SetTest() {
        students = new ArrayList<Student>();
    }

    /*
     * 用于往 students 中添加學生
     */
    public void testAdd() {
        //創(chuàng)建一個學生對象,并通過調(diào)用 add 方法,添加到學生管理 List 中
        Student st1 = new Student("1", "張三");
        students.add(st1);

        //添加到 List 中的類型均為 Object,所以取出時還需要強轉(zhuǎn)

        Student st2 = new Student("2","李四");
        students.add(st2);

        Student[] student = {new Student("3", "王五"),new Student("4", "馬六")};
        students.addAll(Arrays.asList(student));

        Student[] student2 = {new Student("5", "周七"),new Student("6", "趙八")};
        students.addAll(Arrays.asList(student2));

    }

    /**
     * 通過 for each 方法訪問集合元素
     * @param args
     */
    public void testForEach() {
        System.out.println("有如下學生(通過 for each):");
        for(Object obj:students){
            Student st = (Student)obj;
            System.out.println("學生:" + st.id + ":" + st.name);
        }
    }

    public static void main(String[] args){
        SetTest st = new SetTest();
        st.testAdd();
        st.testForEach();
        PD pd = new PD("1","張老師");
        System.out.println("請:" + pd.name + "選擇小組成員!");
        //創(chuàng)建一個 Scanner 對象,用來接收從鍵盤輸入的學生 ID
        Scanner console = new Scanner(System.in);

        for(int i = 0;i < 3; i++){
            System.out.println("請輸入學生 ID");
            String studentID = console.next();
            for(Student s:st.students){
                if(s.id.equals(studentID)){
                    pd.students.add(s);
                }
            }
        }
        st.testForEachForSer(pd);
        // 關(guān)閉 Scanner 對象
        console.close();
    }
    //打印輸出,老師所選的學生!Set 里遍歷元素只能用 foreach 和 iterator
    //不能使用 get() 方法,因為它是無序的,不能想 List 一樣查詢具體索引的元素
    public void testForEachForSer(PD pd){
        for(Student s: pd.students) {
        System.out.println("選擇了學生:" + s.id + ":" + s.name);
        }
    }

}

HashMap類

HashMap 是基于哈希表的 Map 接口的一個重要實現(xiàn)類。HashMap 中的 Entry 對象是無序排列的,Key 值和 value 值都可以為 null,但是一個 HashMap 只能有一個 key 值為 null 的映射(key 值不可重復(fù))。

下面我們通過代碼來學習 Map 中的方法吧。都有過選課經(jīng)歷吧,我們就用 Map 來管理課程吧

創(chuàng)建一個Course類

public class Course {
    public String id;
    public String name;
    public Course(String id, String name){
        this.id = id;
        this.name = name;
    }
}

創(chuàng)建一個MapTest類:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class MapTest {

    /**
     * 用來承裝課程類型對象
     */
    public Map<String, Course> courses;

    /**
     * 在構(gòu)造器中初始化 courses 屬性
     * @param args
     */
    public MapTest() {
        this.courses = new HashMap<String, Course>();
    }

    /**
     * 測試添加:輸入課程 ID,判斷是否被占用
     * 若未被占用,輸入課程名稱,創(chuàng)建新課程對象
     * 并且添加到 courses 中
     * @param args
     */
    public void testPut() {
        //創(chuàng)建一個 Scanner 對象,用來獲取輸入的課程 ID 和名稱
        Scanner console = new Scanner(System.in);

        for(int i = 0; i < 3; i++) {
            System.out.println("請輸入課程 ID:");
            String ID = console.next();
            //判斷該 ID 是否被占用
            Course cr = courses.get(ID);
            if(cr == null){
                //提示輸入課程名稱
                System.out.println("請輸入課程名稱:");
                String name = console.next();
                //創(chuàng)建新的課程對象
                Course newCourse = new Course(ID,name);
                //通過調(diào)用 courses 的 put 方法,添加 ID-課程映射
                courses.put(ID, newCourse);
                System.out.println("成功添加課程:" + courses.get(ID).name);
            }
            else {
                System.out.println("該課程 ID 已被占用");
                continue;
            }
        }
    }

    /**
     * 測試 Map 的 keySet 方法
     * @param args
     */

    public void testKeySet() {
        //通過 keySet 方法,返回 Map 中的所有鍵的 Set 集合
        Set<String> keySet = courses.keySet();
        //遍歷 keySet,取得每一個鍵,在調(diào)用 get 方法取得每個鍵對應(yīng)的 value
        for(String crID: keySet) {
            Course cr = courses.get(crID);
            if(cr != null){
                System.out.println("課程:" + cr.name);
            }
        }
    }

    /**
     * 測試刪除 Map 中的映射
     * @param args
     */
    public void testRemove() {
        //獲取從鍵盤輸入的待刪除課程 ID 字符串
        Scanner console = new Scanner(System.in);
        while(true){
            //提示輸出待刪除的課程 ID
            System.out.println("請輸入要刪除的課程 ID!");
            String ID = console.next();
            //判斷該 ID 是否對應(yīng)的課程對象
            Course cr = courses.get(ID);
            if(cr == null) {
                //提示輸入的 ID 并不存在
                System.out.println("該 ID 不存在!");
                continue;
            }
            courses.remove(ID);
            System.out.println("成功刪除課程" + cr.name);
            break;
        }
    }

    /**
     * 通過 entrySet 方法來遍歷 Map
     * @param args
     */
    public void testEntrySet() {
        //通過 entrySet 方法,返回 Map 中的所有鍵值對
        Set<Entry<String,Course>> entrySet = courses.entrySet();
        for(Entry<String,Course> entry: entrySet) {
            System.out.println("取得鍵:" + entry.getKey());
            System.out.println("對應(yīng)的值為:" + entry.getValue().name);
        }
    }

    /**
     * 利用 put 方法修改 Map 中的已有映射
     * @param args
     */
    public void testModify(){
        //提示輸入要修改的課程 ID
        System.out.println("請輸入要修改的課程 ID:");
        //創(chuàng)建一個 Scanner 對象,去獲取從鍵盤上輸入的課程 ID 字符串
        Scanner console = new Scanner(System.in);
        while(true) {
            //取得從鍵盤輸入的課程 ID
            String crID = console.next();
            //從 courses 中查找該課程 ID 對應(yīng)的對象
            Course course = courses.get(crID);
            if(course == null) {
                System.out.println("該 ID 不存在!請重新輸入!");
                continue;
            }
            //提示當前對應(yīng)的課程對象的名稱
            System.out.println("當前該課程 ID,所對應(yīng)的課程為:" + course.name);
            //提示輸入新的課程名稱,來修改已有的映射
            System.out.println("請輸入新的課程名稱:");
            String name = console.next();
            Course newCourse = new Course(crID,name);
            courses.put(crID, newCourse);
            System.out.println("修改成功!");
            break;
        }
    }

    public static void main(String[] args) {
        MapTest mt = new MapTest();
        mt.testPut();
        mt.testKeySet();
        mt.testRemove();
        mt.testModify();
        mt.testEntrySet();

    }
}

參考鏈接

在線文檔-jdk-zh

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容