Java Day9

集合

目的

1.清楚java中集合的含義
2.明白集合與數(shù)組的區(qū)別
3.了解集合中的一些方法

技術(shù)

數(shù)組:存儲多個對象
int[] score = {1,2,3};
int[] score = new int[10];
弊端:數(shù)組的長度不可變 內(nèi)容可變

實際開發(fā)中需要一個能夠隨時改變的數(shù)組 -> 集合 Collection
數(shù)組:有序 可重復
集合:無序性 互異性
映射:一對一 多對一
Collection 抽象的接口 定義集合的相關(guān)操作
1.List(接口) 列表 數(shù)組
ArrayList
LinkedArrayList
2.Set(集合)
HashSet
Map接口 映射關(guān)系 Key-Value 鍵值對 鍵不能相同 值可以相同

集合的元素個數(shù)是可變的
添加元素
add
addAll
刪除元素
插入元素
訪問元素

技術(shù)運用

  • Collection接口的方法
        Collection<String> list = new ArrayList();
        list.add("Jack");
        list.add("Merry");
        System.out.println(list);

刪除一個對象

        list.remove("Jack");
        System.out.println(list);

獲取元素個數(shù)
System.out.println(list.size());

判斷是否包含一個元素

        if (list.contains("Merry")){
            System.out.println("有Merry");
        }else {
            System.out.println("沒有Merry");
        }

判斷是否為空

        if (list.isEmpty()){
            System.out.println("是空的");
        }else {
            System.out.println("不為空");
        }

判斷兩個集合是否相同

        Collection<String> t2 = new ArrayList<>();
        t2.add("Merry");
        t2.add("Jack");

        if (list.equals(t2)){
            System.out.println("兩個集合相同");
        }else{
            System.out.println("兩個集合不相同");
        }

清空

        list.clear();
        System.out.println(list);
  • 集合的遍歷
    1.使用Iterator來遍歷
    hasNext 判斷是否有元素
    next 獲取下一個對象
    remove 刪除當前遍歷過后的對象
        Iterator iterator = t2.iterator();

        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
  1. forEach
        for (String obj:t2){
            System.out.println(obj);
        }
  1. for i
        for (int i = 0;i < t2.size(); i++){
            System.out.println(((ArrayList<String>) t2).get(i));
        }
  • List接口 extends Collection
    // ArrayList 連續(xù)的內(nèi)存空間
    // 優(yōu)點;訪問方便 get(0); 缺點:刪除 添加
    // LinkedArrayList 內(nèi)部使用鏈表實現(xiàn) 不一定連續(xù) (基本不連續(xù))
    // 優(yōu)點:增加 刪除 效率高 缺點:訪問
    // 集合里面只能存放對象 不能存放基本數(shù)據(jù)類型
    // byte char int long float double boolean (八種基本數(shù)據(jù)類型)
    // 包裝類
    // Byte Char Integer Long Float Double Boolean
    // 自動將基本數(shù)據(jù)類型包裝為對應(yīng)的類
        ArrayList<Integer> score = new ArrayList<>();
        score.add(2);
        score.add(3);     // 在末尾添加
        score.add(0,1); // 在指定位置插入
        System.out.println(score);

訪問指定元素
score.get(1);

修改一個元素

        score.set(0,0);
        System.out.println(score);

刪除

        score.remove(0);  // 刪除指定位置的元素
        System.out.println(score);

        score.remove((Integer)2);  // 刪除指定的對象
        System.out.println(score);

        score.clear();            // 刪除所有 清空
        System.out.println(score);
        ArrayList<Integer> a2 = new ArrayList<>();
        a2.add(1);
        a2.add(2);
        a2.add(3);
        System.out.println("---------------");

將一個集合里面的內(nèi)容添加到當前集合中

        score.addAll(a2);
        System.out.println(score);

取兩個集合的交集

        ArrayList<Integer> a3 = new ArrayList<>();
        a3.add(1);
        a3.add(2);

        score.retainAll(a3);  // 取兩個集合的交集
        System.out.println(score);

訪問某個對象在集合里面的索引

        ArrayList<Integer> a4 = new ArrayList<>();
        a4.add(1);
        a4.add(2);
        a4.add(2);
        a4.add(1);
        System.out.println(a4.indexOf(1));   // 第一次出現(xiàn)
        System.out.println(a4.lastIndexOf(1)); // 最后一次出現(xiàn)
        System.out.println(a4.indexOf(5));       //  不存在則返回 -1

將ArrayList轉(zhuǎn)化為普通數(shù)組

        Integer[] objects = new Integer[a4.size()];
        a4.toArray(objects);
        for (Integer i:objects) {
            System.out.println(i);
        }
       
        Object[] objects1 = a4.toArray();
        for(Object i:objects1){
            System.out.println(i);
        }
        

        Iterator iterator = a4.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

獲取集合某個范圍的子集合

        List<Integer> integer = a4.subList(1,3);
        System.out.println(integer);
  • Lambda表達式
    ArrayList<Integer> nums = new ArrayList<>();
    nums.add(1);
    nums.add(2);
    nums.add(3);
    nums.add(4);
    nums.removeIf( ele -> ele % 2 == 0);
    System.out.println(nums);
     1.使用方式:定義一個類實現(xiàn)接口
    ArrayClass ac = new ArrayClass();
    int[] num = {1,2,3,4,5,6};
    aaClass aa = new aaClass();
    ac.test(num,aa);
        // 閉包 enclosure 把函數(shù)作為一個方法的參數(shù)
class ArrayClass{
    public void test(int[] target, Show show) {
        for (int element:target){
            show.customShow(element);
        }
    }
}

// 必須是接口 這個接口里面只有一個方法
interface Show{
    void customShow(int element);
}

class aaClass implements Show{

    @Override
    public void customShow(int element) {
        System.out.println(element);
    }
}
     2.使用匿名類
    ArrayClass ac = new ArrayClass();
    int[] num = {1,2,3,4,5,6};
    ac.test(num, new Show() {
        @Override
        public void customShow(int element) {
            System.out.println(element);
        }
    });


     3.使用Lambda表達式
     如果參數(shù)是一個接口類對象,且接口里面只有一個方法
     把這個方法作為參數(shù)傳遞過去 可以省略方法名
    ArrayClass ac = new ArrayClass();
    int[] num = {1,2,3,4,5,6};
    ac.test(num,(int element) -> {
        System.out.println(element);
    });

     4.如果只有一個參數(shù) 參數(shù)類型可以省略
    ArrayClass ac = new ArrayClass();
    int[] num = {1,2,3,4,5,6};
    ac.test(num,element -> {
        System.out.println(element);
    });

     5.如果代碼塊里面只有一行語句 大括號可以省略
    ArrayClass ac = new ArrayClass();
    int[] num = {1,2,3,4,5,6};
    ac.test(num,element -> System.out.println(element));
  • sort方法的使用及自己創(chuàng)建一個比較器
    自己創(chuàng)建一個比較器
    //什么時候需要自己創(chuàng)建一個比較器
    // 如果系統(tǒng)提供的方法不能完成我們的比較
class abCompare implements Comparator{
    @Override
    public int compare(Object o, Object t1) {
        int mo = (int)o;
        int mt1 = (int)t1;
        return mo - mt1;
    }
}

sort方法的使用

 ArrayList<Integer> a1 = new ArrayList<>();
        a1.add(2);
        a1.add(1);
        a1.add(4);
        a1.add(3);

       // a1.sort(Comparator.comparingInt(Integer::intValue));

       // a1.sort(new abCompare());

//        a1.sort(new Comparator<Integer>() {
//            @Override
//            public int compare(Integer integer, Integer t1) {
//                return integer - t1;
//            }
//        });

        a1.sort((Integer i1, Integer i2) ->{
            return i1 - i2;
        });
        System.out.println(a1);
    }
}

// 創(chuàng)建一個類Person: name age 屬性
// 創(chuàng)建ArrayList對象保存多個Person對象
// 統(tǒng)計年齡大于30的人數(shù)
// 統(tǒng)計名字中有張的人數(shù)

import java.util.ArrayList;

public class MyClass {
    public static void main(String[] args){
        ArrayList<Person> people = new ArrayList<>();

        Person xw = new Person("小王",16);
        Person xl = new Person("小李",39);
        Person zs = new Person("張三",35);

        people.add(xw);
        people.add(xl);
        people.add(zs);

        int ageCount = 0;
        int nameCount = 0;

        for (Person p :
                people) {
            if (p.age > 30){
                ageCount++;
            }
            if (p.name.contains("張")){
                nameCount++;
            }
        }
        System.out.println("姓張的人有"+nameCount+"個"+"  年齡大于30歲的有"+ageCount+"個");
    }
}
class Person {
    String name;
    int age;

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

心得

今天學習了集合的使用方法,感覺能靈活使用集合與數(shù)組的話,在以后編寫程序的過程中,必然能夠輕松許多。當然首先應(yīng)該了解其中常用的方法,這樣使用起來才能得心應(yīng)手,雖然有點乏味,但是也沒有辦法,這是必須經(jīng)歷的過程,挺過去了自然就好了。

?著作權(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)容