Java--集合

集合

集合的概念

一、概念:对象的容器,实现了对对象常用的操作,类似数组功能

二、集合和数组区别:

  • (1)数组长度固定,集合长度不固定
  • (2)数组可以存储基本类型和引用类型,集合只能存储引用类型

位置:java.util.*;

三、迭代器:专门用来遍历集合一种方式

hasNext():有一个元素吗?如果有 返回true,否则false

next():获取下一个元素

remove():删除元素

四:List接口的特点:有序有下标,可以重复

五:List常见实现类

ArrayList:

源码分析:DEFAULT_CAPACITY = 10; 默认容量

注意:如果没有向集合中添加任何元素时,容量0,添加一个元素之后,容量 10 每次扩容大小是原来的1.5倍

elementData 存放元素的数组

size 实际元素个数

add() 添加元素

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(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);
    }

Collection接口

在这里插入图片描述

  • Collection:该体系结构的根接口,代表一组对象,称为"集合"
  • List接口的特点:有序、有下标、元素可重复
  • Set接口的特点:无序、无下标、元素不能重复

Collection父接口

  • 特点:代表一组任意类型的对象,无序、无下标、不能重复
  • 方法:
    • boolean add(Object obj) -->添加一个对象。
    • boolean addAll(Collection c) -->将一个集合中的所有对象添加到此集合中。
    • void clear() -->清空此集合中的所有对象
    • boolean contains(Object o) -->检查此集合中是否包含o对象
    • boolean equals(Object o) -->比较此集合是否与指定对象相等。
    • boolean isEmpty() -->判断此 集合是否为空
    • boolean remove(Object o) -->在此集合中移除o对象
    • int size() -->返回此集合中的元素个数。
    • Object[] toArray() -->将此集合转换成数组。

代码块:

CollectionDemo01

package com.huai.Collection;
/*
* Collection的使用
* (1)添加元素
* (2)删除元素
* (3)遍历元素
* (4)判断
*
* */

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

public class collectionDemo01 {
    public static void main(String[] args) {
        //创建集合
        Collection collection = new ArrayList();
        //(1)添加元素
        collection.add("苹果");
        collection.add("西瓜");
        collection.add("榴莲");
        System.out.println("元素个数:"+collection.size());
        System.out.println(collection);

        //(2)删除元素
//        collection.remove("榴莲");
//        collection.clear();
//        System.out.println("删除之后"+collection.size());

        //(3)遍历元素
        //3.1使用增强for
        System.out.println("========使用增强for========");
        for (Object o : collection) {
            System.out.println(o);
        }

        //3.2使用迭代器(迭代器专门用来遍历集合的一种方式)
        //hasNext();有没有下一个元素
        //next();获取下一个元素
        //remove();删除当前元素
        System.out.println("========使用迭代器========");
        Iterator it = collection.iterator();
        while (it.hasNext()){
            Object o = (String)it.next();
            System.out.println(o);
            //不能使用collection删除方法
            //collection.remove(o)
            //it.remove();
        }
        System.out.println("元素个数:"+collection.size());

        //(4)判断
        System.out.println(collection.contains("西瓜"));
        System.out.println(collection.isEmpty());

    }
}

CollectionDemo02

package com.huai.Collection;
/*
* Collection的使用:保存学生信息
*
* */

import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class collectionDemo02 {
    public static void main(String[] args) {
        //新建Collection对象
        Collection collection = new ArrayList();
        Student s1 = new Student("大伟",23);
        Student s2 = new Student("山姆",22);
        Student s3 = new Student("噶辉",23);
        //1.添加数据
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        System.out.println("元素个数:"+collection.size());
        System.out.println(collection.toString());

        //2.删除
        //collection.remove(s1);
        //collection.remove(new Student("山姆",22));
        //collection.clear();
        //System.out.println("删除之后:"+collection.size());

        //3.遍历
        //3.1增强for
        System.out.println("======使用增强for=======");
        for (Object o : collection) {
            Student s = (Student)o;
            System.out.println(s.toString());
        }

        //3.2迭代器:hasNext();  next();  remove();   迭代过程中不能使用collection的删除方法
        System.out.println("======使用迭代器=======");
        Iterator it = collection.iterator();
        while (it.hasNext()){
            Student s = (Student)it.next();
            System.out.println(s.toString());
        }

        //4.判断
        System.out.println(collection.contains(s1));
        System.out.println(collection.isEmpty());

    }
}

Student

package com.huai.Collection;

//学生类
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 +
                '}';
    }
}

List接口与实现类

list接口

特点:有序、有下标、元素可以重复

方法:

  • void add(int index,Object o) -->在index位置插入对象o
  • boolean addAll(int index,Colletion c) -->将一个集合中的元素添加到此集合中的index位置
  • Object get(int index) -->返回集合中指定位置的元素
  • List subList(int formIndex,int toIndex) -->返回formIndex和toIndex之间的结合元素

list实现类

ArrayList【重点】:
  • 数组结构实现,查询快、增删慢;
  • JDK1.2版本,运行效率快、线程不安全
package com.huai.ListDemo;

import com.huai.Collection.Student;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

/*
* ArrayList的使用
* 存储结构:数组、查找遍历速度快、增删慢
*
*
* */
public class ArrayListDemo01 {
    public static void main(String[] args) {
        //创建集合 size 0  容量0  扩容原来的1.5倍
        ArrayList arrayList = new ArrayList<>();
        //1.添加元素
        Student s1 = new Student("大伟",23);
        Student s2 = new Student("山姆",22);
        Student s3 = new Student("噶辉",23);
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        System.out.println("元素个数:"+arrayList.size());
        System.out.println(arrayList.toString());
        //2.删除元素
        //arrayList.remove(s1);
        arrayList.remove(new Student("大伟",23));//equals(this==obj)
        System.out.println("删除之后:"+arrayList.size());

        //3.遍历元素【重点】
        //3.1使用迭代器
        System.out.println("=======3.1使用列表迭代器========");
        Iterator it = arrayList.iterator();
        while (it.hasNext()){
            Student s = (Student) it.next();
            System.out.println(s.toString());
        }

        //3.2列表迭代器
        ListIterator lit = arrayList.listIterator();
        System.out.println("=======3.2使用列表迭代器========");
        while (lit.hasNext()){
            Student s= (Student)lit.next();
            System.out.println(s.toString());
        }

        System.out.println("=======3.3使用列表迭代器========");
        while (lit.hasPrevious()){
            Student s = (Student)lit.previous();
            System.out.println(s.toString());
        }

        //4.判断
        System.out.println(arrayList.contains(new Student("山姆",22)));
        System.out.println(arrayList.isEmpty());

        //5.查找
        System.out.println(arrayList.indexOf(new Student("山姆",22)));

    }
}


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

import java.util.Enumeration;
import java.util.Vector;

/*
*  演示Vector集合的使用
*  存储结构:数组
*
* */
public class vectorDemo01 {
    public static void main(String[] args) {
        //创建集合
        Vector vector = new Vector<>();
        //1.添加元素
        vector.add("草莓");
        vector.add("芒果");
        vector.add("西瓜");
        System.out.println("元素个数:"+vector.size());

        //2.删除
//        vector.remove(0);
//        vector.remove("西瓜");
//        vector.clear();

        //3.遍历
        //使用枚举器
        Enumeration en = vector.elements();
        while(en.hasMoreElements()){
            String o = (String)en.nextElement();
            System.out.println(o);
        }

        //4.判断
        System.out.println(vector.contains("西瓜"));
        System.out.println(vector.isEmpty());

        //Svector其他方法
        //firsetElement  lastElementAt();


    }
}

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.huai.GenericsDemo;

import com.huai.Collection.Student;

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

public class GenericsDemo02 {
    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 s : arrayList) {
            System.out.println(s);
        }
        
        ArrayList<Student> arrayList2 = new ArrayList<Student>();
        Student s1 = new Student("大伟", 23);
        Student s2 = new Student("山姆", 22);
        Student s3 = new Student("噶辉", 22);
        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());
        }

    }
}

Set接口与实现类

  • 特点:无序、无下标、元素不可重复
  • 方法:全部继承Collection中的方法
HashSet【重点】:
  • 基于HashCode计算元素存放位置
  • 当存入元素的哈希码相同时,会调用equals进行确认,如结果为true,则拒绝后者存入
package com.huai.SetDemo;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/*
* 测试set接口的使用
* 特点:1.无序、无下标 2.不能重复
*
* */

public class SetDemo01 {
    public static void main(String[] args) {
        //创建集合
        Set<String> set = new HashSet<>();

        //1.添加数据
        set.add("小米");
        set.add("苹果");
        set.add("华为");
        //set.add("华为");
        System.out.println("数据个数:"+set.size());
        System.out.println(set.toString());

        //2.删除数据
//        set.remove("小米");
//        System.out.println(set.toString());

        //3.遍历【重点】
        //3.1增强for
        System.out.println("========增强for========");
        for (String  s : set) {
            System.out.println(s);
        }

        //3.2 迭代器
        System.out.println("========迭代器========");
        Iterator<String> it = set.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }

        //4.判断
        System.out.println(set.contains("华为"));
        System.out.println(set.isEmpty());

    }
}

TreeSet:
  • 基于排序顺序实现元素不重复
  • 实现了SortedSet接口,对集合元素自动排序
  • 元素对象的类型必须实现Comparable接口,指定排序规则
  • 通过CompareTo方法确定是否为重复元素
package com.huai.TreeSetDemo;
/*
* 使用TreeSet集合实现字符串按照长度进行排序
* helloworld  zhangsan  lisi  wangwu   beijing   xian   nanjing
* 使用Comparator接口实现定制比较
*
* */


import sun.reflect.generics.tree.Tree;

import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetDemo04 {
    public static void main(String[] args) {
        //创建集合,并指定比较规则
        TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int n1 = o1.length()-o2.length();
                int n2 = o1.compareTo(o2);

                return n1==0?n2:n1;
            }
        });

        //添加数据
        treeSet.add("helloworld");
        treeSet.add("phone");
        treeSet.add("lisi");
        treeSet.add("zhangsan");
        treeSet.add("beijing");
        treeSet.add("wangwu");
        treeSet.add("nanjing");
        treeSet.add("xian");
        treeSet.add("cat");

        System.out.println(treeSet.toString());
    }
}

Map接口与实现类

在这里插入图片描述

  • 特点:存储一对数据(Key-Value),键:无序、无下标,不允许重复(唯一),值:无序、无下标、允许重复
  • 方法:
    • V put(K key,V value) -->将对象存入到集合中,关联键值。key重复则覆盖原值
    • Object get(Object key) -->根据键获取对应的值
    • Set -->返回所有key。
    • Collection values() -->返回包含所有值的Collection集合
    • Set<Map.Entry<K,V>> -->键值匹配的Set集合
keySet()和entrySet()区别

在这里插入图片描述

HashMap【重点】:
  • JDK1.2版本,线程不安全,运行效率快;允许用null 作为key或是value
存储结构:哈希表
重复依据:键的hashCode()方法和equals方法

源码分析

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//hashMap初始容量大小
static final int MAXIMUM_CAPACITY = 1 << 30;//hashmap的数组最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认加载因子
static final int TREEIFY_THRESHOLD = 8;//jdk1.8 当链表长度大于8时,调整成红黑树
static final int UNTREEIFY_THRESHOLD = 6;//jdk1.8 当链表长度小于6时,调整成链表
static final int MIN_TREEIFY_CAPACITY = 64;//jdk1.8 当链表长度大于8时,并且集合元素个数大于等于6时,调整成红黑树
transient Node<K,V>[] table;//哈希表中的数组 table指的是哈希桶【重点】
size;//元素个数

无参构造

public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

put方法

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

总结:

(1)HashMap刚创建时,table是null,为了节省空间,当添加第一个元素时,table容量调整为16
(2)当元素个数大于阈值(16*0.75=12)时,会进行扩容,扩容后大小为原来的2倍,目的是减少调整元素的个数
(3)jdk1.8 当每个链表长度大于8,并且数组元素个数大于等于64时,会调整为红黑树,目的提高执行效率
(4)jdk1.8 当链表长度小于6时,调整成链表
(5)jdk1.8以前,链表是头插入,jdk1.8以后是尾插入
Hashtable:
  • JDK1.0版本,线程安全,运行效率慢,不允许null作为key或是value
Properties:
  • Hashtable的子类,要求key和value都是String。通常用于配置文件的读取
TreeMap:
  • 实现了SortedMap接口(是Map的子接口),可以对key自动排序

Collection工具类

  • 集合工具类,定义了除了存取以外的集合常用方法

  • 方法:

public static void reverse(List<?> list)//反转集合中元素的顺
    
public static void shuffle(List<?> list)//随机重置集合元素的顺序
    
public static void sort(List<T> list)//升序排序(元素类型必须实现Comparable接口)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值