JAVASE基础(十一)

本文详细介绍了Java集合框架,包括Collection接口、List接口与ArrayList、Vector、LinkedList的实现,Set接口与HashSet、TreeSet的使用,Map接口及HashMap、TreeMap的特点,以及泛型和Collections工具类的运用。内容涵盖了集合的基本操作、泛型的原理和优势、集合的排序和比较,以及实用的工具类方法。
摘要由CSDN通过智能技术生成

一、集合的概念

概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。

和数组的区别:

(1)数组长度固定,集合长度不固定

(2)数组可以存储基本类型和引用类型,集合只能存储引用类型

位置:java.util.*;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RUflhVRL-1636706387687)(C:\Users\de’l’l\AppData\Roaming\Typora\typora-user-images\image-20211102105654826.png)]

二、Collecting接口

特点:代表任意一组任意类型的对象,无序、无下标、不能重复。

方法:

(1)boolean add(Object obj):添加一个对象

(2)boolean addAll(Collection c):将一个集合中的所有对象添加到此集合中

(3)void clear():清空此集合中的所有集合

(4)boolean contains(Object o):检查此集合中是否包含o对象

(5)boolean equals(Object o):比较此集合是否与指定对象相等

(6)boolean isEmpty():判断此集合是否为空

(7)boolean remove(Object o):在此集合中移除o对象

(8)int size():返回此集合中的元素个数

(9)Object[] toArray():将此集合转换成数组

Collection接口的使用(1):

package com.collection;

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

/**
 * Collection接口的使用
 * (1)添加元素
 * (2)删除元素
 * (3)遍历元素
 * (4)判断
 */
public class Demo01 {
    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());
        System.out.println(collection);
        //3.遍历元素
        //(1)增强for
        for (Object object: collection) {
            System.out.println(object);
        }
        //(2)迭代器(专用于遍历集合的一种方式)
        //hasNext():有没有下一个元素
        //next():获取下一个元素
        //remove():删除当前元素
        Iterator it = collection.iterator();
        while (it.hasNext()){
            String s = (String) it.next();
            System.out.println(s);
            //迭代器运行过程中不能使用collection.remove
            //collection.remove();
            //需要使用迭代器删除方法
            //it.remove();
        }
        System.out.println("元素个数:"+collection.size());

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

Collection接口的使用(2):

package com.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 +
                '}';
    }
}
package com.collection;

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

/**
 * Collection的使用:保存学生信息
 */
public class Demo02 {
    public static void main(String[] args) {
        //新建Collection对象
        Collection collection = new ArrayList();
        Student s1 = new Student("张三",20);
        Student s2 = new Student("李四",18);
        Student s3 = new Student("王二",22);
        //1.添加数据
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        System.out.println("元素个数:"+collection.size());
        System.out.println(collection.toString());
        //2.删除
        collection.remove(s1);
        System.out.println("删除之后元素个数:"+collection.size());
        //3.遍历
        //(1)增强for
        for (Object object:collection
             ) {
            Student s = (Student) object;
            System.out.println(s.toString());
        }
        //(2)迭代器 hasNext()  next()  remove();迭代过程中不能使用collection删除方法
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()){
            Student s = (Student)iterator.next();
            System.out.println(s);
        }
        //4.判断
        System.out.println(collection.contains(s1));
        System.out.println(collection.isEmpty());
    }

}

三、List接口与实现类

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

1、方法:

(1)void add(int index,Object o):在index位置插入对象0

(2)boolean addAll(int index,Collection c):将一个集合中的元素添加到此集合中的index位置

(3)Object get(int index):返回集合中指定位置的元素

(4)List subList(int fromIndex,int toIndex):返回fromIndex和toIndex之间的集合元素

List的使用(1):

package com.collection;

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

/**
 * List子接口的使用
 * 特点:1.有序、有下标2.可以重复
 */
public class ListDemo01 {
    public static void main(String[] args) {
        //创建集合对象
        List list = new ArrayList();
        //1.添加元素
        list.add("苹果");
        list.add("小米");
        list.add(0,"华为");
        System.out.println("元素个数:"+list.size());
        System.out.println(list.toString());
        //2.删除
        //list.remove("苹果");
        list.remove(0);
        System.out.println("删除后元素个数:"+list.size());
        System.out.println(list.toString());
        //3.遍历
        //(1)使用for遍历
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        //(2)使用增强for
        for (Object object:list
             ) {
            System.out.println(object);
        }
        //(3)使用迭代器
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //(4)使用列表迭代器,相比iterator,Listiterator可以向前、向后遍历,添加、删除、修改元素
        ListIterator listIterator = list.listIterator();
        //列表迭代器从前往后遍历
        while (listIterator.hasNext()){
            System.out.println(listIterator.nextIndex()+":"+listIterator.next());
        }
        //列表迭代器从后往前遍历
        while (listIterator.hasPrevious()){
            System.out.println(listIterator.previousIndex()+":"+listIterator.previous());
        }
        //4.判断
        System.out.println(list.contains("苹果"));
        System.out.println(list.isEmpty());
        //5.获取位置
        System.out.println(list.indexOf("小米"));
    }
}

List的使用(2):

package com.collection;

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

/**
 * List的使用
 */
public class ListDemo02 {
    public static void main(String[] args) {
        //创建集合
        List list = new ArrayList();
        //1.添加数字数据(自动装箱)
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
        list.add(60);
        System.out.println("元素个数:"+list.size());
        System.out.println(list.toString());
        //2.删除
        //list.remove(0);
        //list.remove((Object) 20);
        list.remove((new Integer(20)));
        System.out.println("删除元素后元素个数:"+list.size());
        System.out.println(list.toString());
        //3.补充方法subList():返回子集合,含头不含尾
        List subList = list.subList(1, 3);
        System.out.println(subList.toString());
    }
}

2、实现类:

(1)ArrayList

:数组结构实现,查询快、增删慢;JDK1.2版本,运行效率快、线程不安全。

ArrayList源码分析:

DEFAULT_CAPACITY = 10;默认容量 注意:如果没有向集合中添加任何元素时,容量为0;添加任意元素后,容量为10。每次扩容大小是原来的1.5倍。

elementData存放元素的数组

size实际元素个数

    @Override
    public boolean equals(Object obj){
        //1.判断是不是同一个对象
        if (this==obj){
            return true;
        }
        //2.判断是否为空
        if (obj==null){
            return false;
        }
        //3.判断是否是Student类型
        if (obj instanceof Student){
            Student s = (Student) obj;
            //4.比较属性
            if (this.name.equals(s.getName())&&this.age==s.getAge()){
                return true;
            }
        }
        //5.不满足条件返回false
        return false;
    }
package com.collection;

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

/**
 * ArrayList的使用
 * 存储结构:数组,查找遍历速度快,增删速度慢
 */
public class ArrayListDemo {
    public static void main(String[] args) {
        //创建集合
        ArrayList<Object> arrayList = new ArrayList<>();
        //1.添加元素
        Student s1 = new Student("刘德华",20);
        Student s2 = new Student("郭富城",22);
        Student s3 = new Student("梁朝伟",18);
        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("刘德华",20));
        System.out.println("删除之后元素个数:"+arrayList.size());
        //3.遍历元素
        //(1)迭代器
        Iterator it = arrayList.iterator();
        while (it.hasNext()){
            Student s = new Student();
            System.out.println(s.toString());
        }
        //(2)列表迭代器
        ListIterator lit = arrayList.listIterator();
        while (lit.hasNext()){
            Student student = (Student)lit.next();
            System.out.println(student.toString());
        }
        //(3)使用列表迭代器逆序
        while (lit.hasPrevious()){
            Student s = (Student) lit.previous();
            System.out.println(s.toString());
        }
        //4.判断
        System.out.println(arrayList.contains(new Student("梁朝伟",18)));//方法重写,所以结果为true
        System.out.println(arrayList.isEmpty());
        //5.查找
        System.out.println(arrayList.indexOf(new Student("梁朝伟",18)));
    }
}

(2)Vector

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

package com.collection;

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

/**
 * 演示Vector集合的使用
 * 存储结构:数组
 */
public class VectorDemo {
    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("西瓜");
//        vector.remove(0);
//        vector.clear();
        //3.遍历
        //使用枚举器
        Enumeration elements = vector.elements();
        while (elements.hasMoreElements()){
            Object o = (String)elements.nextElement();
            System.out.println(o);
        }
        //4.判断
        System.out.println(vector.contains("西瓜"));
        System.out.println(vector.isEmpty());
        //5.Vector其他方法
        //firstElement、lastElement、ElementAt;
    }

}

(3)LinkedList

:链表结构实现,增删快、查询慢。

package com.collection;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

/**
 * LinkedList的使用
 * 存储结构:双向链表
 */
public class LinkedListDemo {
    public static void main(String[] args) {
        //创建集合
        LinkedList linkedList = new LinkedList<>();
        //1.添加元素
        Student s1 = new Student("刘德华",20);
        Student s2 = new Student("郭富城",22);
        Student s3 = new Student("梁朝伟",18);
        linkedList.add(s1);
        linkedList.add(s2);
        linkedList.add(s3);
        System.out.println("元素个数:"+linkedList.size());
        System.out.println(linkedList.toString());
        //2.删除
//        linkedList.remove(s1);
//        System.out.println("删除后元素个数:"+linkedList.size());
//        linkedList.clear();
        //3.遍历
        //(1)for遍历
        for (int i = 0; i < linkedList.size(); i++) {
            System.out.println(linkedList.get(i));
        }
        //(2)增强for遍历
        for (Object object:linkedList
             ) {
            Student s = (Student) object;
            System.out.println(s.toString());
        }
        //3.迭代器
        Iterator iterator = linkedList.iterator();
        while (iterator.hasNext()){
            Student s = (Student) iterator.next();
            System.out.println(s);
        }

        ListIterator listIterator = linkedList.listIterator();
        while (listIterator.hasNext()){
            Student s = (Student) listIterator. next();
            System.out.println(s);
        }
        //4.判断
        System.out.println(linkedList.contains(s1));
        System.out.println(linkedList.isEmpty());
        //5.获取
        System.out.println(linkedList.indexOf(s1));
    }
}

四、泛型和工具类

Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递。

常见形式有泛型类、泛型接口、泛型方法。

语法:<T,…> T称为类型占位符,表示一种引用类型。

好处:(1)提高代码的重用性(2)防止类型转换异常,提高代码的安全性。

1、泛型类

package com.collection;

/**
 * 泛型类
 * 语法:类名<T>
 * T是类型占位符,表示一种引用类型。如果编写多个,使用逗号隔开
 */
public class GenericDemo<T> {
    //使用泛型T
    //1.创建变量
    T t ;

    //2.泛型作为方法的参数
    public void show(T t){
        System.out.println(t);
    }
    //3.泛型作为方法的返回值
    public T getT(){
        return t;
    }
}
package com.collection;

public class TextGeneric {
    public static void main(String[] args) {
        //使用泛型类创建对象
        //注意:1.泛型只能使用引用类型2.不同类型泛型对象之间不能相互复制
        GenericDemo<String> genericDemo = new GenericDemo<String>();
        genericDemo.t = "hello";
        genericDemo.show("hello");
//        String s = genericDemo.getT();
//        System.out.println(s);

        GenericDemo<Integer> genericDemo1 = new GenericDemo<>();
        genericDemo1.t = 100;
        genericDemo1.show(200);
//        Integer integer = genericDemo1.getT();
//        System.out.println(integer);

    }
}

2、泛型接口

package com.collection;

/**
 * 泛型接口
 * 语法:接口名<T>
 * 注意:不能使用泛型创建静态常量
 */
public interface MyInterface<T> {
    String name = "张三";

    T server(T t);

}
package com.collection;

public class MyInterfaceImpl implements MyInterface<String>{

    @Override
    public String server(String t) {
        System.out.println(t);
        return t;
    }
}
package com.collection;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

public class MyInterfaceImpl2<T> implements MyInterface<T>{

    @Override
    public T server(T t) {
        System.out.println(t);
        return t;
    }
}
        MyInterfaceImpl impl = new MyInterfaceImpl();
        impl.server("xxxxx");

        MyInterfaceImpl2<Integer> impl2 = new MyInterfaceImpl2<>();
        impl2.server(1000);

3、泛型方法

package com.collection;

/**
 * 泛型方法
 * 语法:<T>返回值类型
 */
public class MyGenericMethod {

    //泛型方法
    public <T> T show(T t){
        System.out.println("泛型方法");
        return t;
    }

}
        //泛型方法
        MyGenericMethod myGenericMethod = new MyGenericMethod();
        myGenericMethod.show("王");
        myGenericMethod.show(200);
        myGenericMethod.show(3.14);

4、泛型集合

概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致。

特点:1.编译时即可检查,而非运行时抛出异常

2.访问时,不必类型转换(拆箱)

3.不同泛型之间不能相互赋值,泛型不存在多态

package com.collection;

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

public class Demo01 {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("xxx");
        arrayList.add("yyy");
        for (String string:arrayList){
            System.out.println(string);
        }
        
        ArrayList<Student> arrayList2 = new ArrayList<>();
        Student s1 = new Student("刘德华",20);
        Student s2 = new Student("郭富城",22);
        Student s3 = new Student("梁朝伟",18);
        arrayList2.add(s1);
        arrayList2.add(s2);
        arrayList2.add(s3);
        Iterator<Student> iterator = arrayList2.iterator();
        while (iterator.hasNext()){
            Student s = iterator.next();
            System.out.println(iterator);
        }
        
    }
}

五、Set接口与实现类

1、Set子接口

特点:无序、无下标、元素不可重复。

方法:全部继承自Collection中的方法。

package com.collection.Set;

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

/**
 * 测试Set接口的使用
 * 特点:1.无序,没有下标2.不能重复
 */
public class Demo01 {
    public static void main(String[] args) {
        //创建集合
        Set<String> set = new HashSet<>();
        //1.添加数据
        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.遍历
        //(1)增强for
        for (String string:set
             ) {
            System.out.println(string);
        }
        //(2)迭代器
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //4.判断
        System.out.println(set.contains("华为"));
        System.out.println(set.isEmpty());
    }
}

2、Set实现类

(1)HashSet:

基于HashCode计算元素存放位置。

当存入元素的哈希码相同时,会调用equals进行确认,如结果为true,则拒绝后者存入。

package com.collection.Set;

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

/**
 * HashSet集合的使用
 * 存储结构:哈希表(数组+链表+红黑树)
 */
public class Demo02 {
    public static void main(String[] args) {
        //新建集合
        HashSet<String> hashSet = new HashSet<>();
        //1.添加元素
        hashSet.add("刘德华");
        hashSet.add("梁朝伟");
        hashSet.add("林志玲");
        hashSet.add("周润发");
        System.out.println("元素个数:"+hashSet.size());
        System.out.println(hashSet.toString());
        //2.删除
        hashSet.remove("刘德华");
        System.out.println("删除之后:"+hashSet.size());
        //3.遍历
        //(1)增强for
        for (String string:hashSet
             ) {
            System.out.println(string);
        }
        //(2)迭代器
        Iterator<String> iterator = hashSet.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //4.判断
        System.out.println(hashSet.contains("郭富城"));
        System.out.println(hashSet.isEmpty());
    }
}
package com.collection.Set;

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

/**
 * HashSet的使用
 * 存储结构:哈希表(数组+链表+红黑树)
 * 存储过程:(1)根据hashcode计算保存的位置,如果此位置为空,则直接保存,如果不为空则执行第二步
 * (2)再执行equals方法。如果equals方法为true,则认为重复,否则,形成链表
 */
public class Demo03 {
    public static void main(String[] args) {
        //创建集合
        HashSet<Person> persons = new HashSet<>();
        //1.添加数据
        Person p1 = new Person("刘",20);
        Person p2 = new Person("林",22);
        Person p3 = new Person("梁",25);
        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        //persons.add(p3);//重复,添加不成功。重写hashcode和equals方法后添加成功。
        System.out.println("元素个数:"+persons.size());
        System.out.println(persons.toString());
        //2.删除
//        persons.remove(p1);
//        persons.remove(new Person("林",22));//重写方法前无法删除,重写后可以
//        System.out.println("删除之后:"+persons.size());
//        System.out.println(persons.toString());
        //3.遍历
        //(1)增强for
        for (Person p:persons
             ) {
            System.out.println(p);
        }
        //(2)迭代器
        Iterator<Person> iterator = persons.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //4.判断
        System.out.println(persons.contains(p1));
        System.out.println(persons.isEmpty());
    }

}

(2)TreeSet:

基于排列顺序实现元素不重复。

实现了SortedSet接口,对集合元素自动排序。

元素对象的类型必须实现Comparable接口,指定排序规则。

通过ComparableTo方法确定是否为重复元素。

package com.collection.Set;

import java.util.Iterator;
import java.util.TreeSet;

/**
 * TreeSet的使用
 * 存储结构:红黑树
 */
public class Demo04 {
    public static void main(String[] args) {
        //创建集合
        TreeSet<String> treeSet = new TreeSet<>();
        //1.添加元素
        treeSet.add("xyz");
        treeSet.add("abc");
        treeSet.add("hello");
        System.out.println("元素个数:"+treeSet.size());
        System.out.println(treeSet.toString());
        //2.删除
//        treeSet.remove("xyz");
//        System.out.println("删除之后:"+treeSet.toString());
        //3.遍历
        //(1)增强for
        for (String string:treeSet
             ) {
            System.out.println(string);
        }
        //(2)迭代器
        Iterator<String> iterator = treeSet.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //4.判断
        System.out.println(treeSet.contains("abc"));
        System.out.println(treeSet.isEmpty());

    }
}
package com.collection.Set;

import java.util.Objects;

public class Person implements Comparable<Person>{
    private String name;
    private int age;

    public Person() {
    }

    public Person(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 "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int hashCode() {
        int n1 = this.name.hashCode();
        int n2 = this.age;

        return n1+n2;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    //先按姓名比,然后再按年龄比
    @Override
    public int compareTo(Person o) {
        int n1 = this.getName().compareTo(o.getName());
        int n2 = this.age-o.getAge();

        return n1==0?n2:n1;
    }
}
package com.collection.Set;

import java.util.Iterator;
import java.util.TreeSet;

/**
 * 使用TreeSet保存数据
 * 存储结构:红黑树
 * 要求:元素必须要实现Comparable接口,CompareTo()方法返回值为0,认为是重复元素
 */
public class Demo05 {
    public static void main(String[] args) {
        //创建集合
        TreeSet<Person> persons = new TreeSet<>();
        //1.添加元素
        Person p1 = new Person("xyz",20);
        Person p2 = new Person("hello",22);
        Person p3 = new Person("zhangsan",25);
        Person p4 = new Person("zhangsan",20);
        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(p4);
        System.out.println("元素个数:"+persons.size());
        System.out.println(persons.toString());
        //2.删除
//        persons.remove(p1);
//        persons.remove(new Person("xyz",20));//删除成功,因为重写了方法,比较的是名字和年龄
//        System.out.println(persons.size());
        //3.遍历
        //(1)增强for
        for (Person person:persons
             ) {
            System.out.println(person);
        }
        //(2)迭代器
        Iterator<Person> iterator = persons.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //4.判断
        System.out.println(persons.contains(p1));
        System.out.println(persons.isEmpty());
    }
}
package com.collection.Set;

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

/**
 * TreeSet的使用
 * Comparator:实现定制比较(比较器)
 * Comparable:可比较的
 */
public class Demo06 {
    public static void main(String[] args) {
        //创建集合,并指定比较规则
        TreeSet<Person> persons = new TreeSet<>(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                int n1 = o1.getAge()-o2.getAge();
                int n2 = o1.getName().compareTo(o2.getName());
                return n1==0?n2:n1;
            }
        });

        Person p1 = new Person("xyz",20);
        Person p2 = new Person("hello",22);
        Person p3 = new Person("zhangsan",25);
        Person p4 = new Person("lisi",25);
        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(p4);
        System.out.println(persons.toString());
    }
}

(3)案例:定制比较

package com.collection.Set;

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

/**
 * 要求:使用TreeSet集合实现字符串按长度进行排序
 * helloworld zhang lisi wangwu beijing xian nanjing
 * Comparator接口实现定制比较
 */
public class Demo07 {
    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("pingguo");
        treeSet.add("lisi");
        treeSet.add("zhangsan");
        treeSet.add("beijing");
        treeSet.add("cat");
        treeSet.add("nanjing");
        treeSet.add("xian");
        System.out.println(treeSet.toString());

    }
}

六、Map接口与实现类

1、Map父接口

特点:存储一对数据,无序、无下标,键不可重复,值可重复。

方法:

(1)V put(K key,V value)//将对象存入到集合中。key重复则覆盖原值。

(2)Object get(Object key)//根据键获取对应的值。

(3)Set //返回所有key。

(4)Collection values()//返回包含所有值的Collection集合。

(5)Set<Map.Entry<K,V>>//键值匹配的Set集合

package com.collection.map;

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

/**
 * Map接口的使用
 * 特点:(1)存储键值对(2)键不能重复,值可以重复(3)无序
 */
public class Demo01 {
    public static void main(String[] args) {
        //创建Map集合
        Map<String,String> map = new HashMap<>();
        //1.添加元素
        map.put("cn","中国");
        map.put("uk","英国");
        map.put("usa","美国");
        System.out.println("元素个数:"+map.size());
        System.out.println(map.toString());
        //2.删除
        map.remove("usa");
        System.out.println("删除之后:"+map.size());
        System.out.println(map.toString());
        //3.遍历
        //(1)使用KeySet();
//        Set<String> keySet = map.keySet();
        for (String key:map.keySet()
             ) {
            System.out.println(key+"--"+map.get(key));
        }
        //(2)使用entrySet()方法
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String,String> entry:entries
             ) {
            System.out.println(entry.getKey()+"--"+entry.getValue());
        }
        //4.判断
        System.out.println(map.containsKey("cn"));
        System.out.println(map.containsValue("泰国"));

    }
}

2、Map集合的实现类

(1)HashMap

:JDK1.2版本,线程不安全,运行效率快;允许用null作为key或是value。

package com.collection.map;

import java.util.Objects;

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

    public Student() {
    }

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

    public String getName() {
        return name;
    }

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

    public int getStuNo() {
        return stuNo;
    }

    public void setStuNo(int stuNo) {
        this.stuNo = stuNo;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return stuNo == student.stuNo && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, stuNo);
    }

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

}
package com.collection.map;

import com.collection.set.Person;

import java.util.HashMap;
import java.util.Map;

/**
 * HashMap的使用
 * 存储结构:哈希表(数组+链表+红黑树)
 */
public class Demo02 {
    public static void main(String[] args) {
        //创建集合
        HashMap<Student,String> students = new HashMap<>();
        //刚创建hashmap后没有添加元素table=null size=0,目的节省空间
        //1.添加元素
        Student s1 = new Student("赵",100);
        Student s2 = new Student("钱",101);
        Student s3 = new Student("孙",102);
        students.put(s1,"北京");
        students.put(s2,"上海");
        students.put(s3,"杭州");
        students.put(new Student("孙",102),"杭州");//在堆中地址不同,可添加成功,重写hashcode和equals方法后不能添加成功
        System.out.println("元素个数:"+students.size());
        System.out.println(students.toString());
        //2.删除
        students.remove(s1);
        System.out.println("删除之后:"+students.size());
        //3.遍历
        //(1)使用keySet()
        for (Student key:students.keySet()
             ) {
            System.out.println(key.toString()+"--"+students.get(key));
        }
        //(2)使用entrySet()
        for (Map.Entry<Student,String> entry:students.entrySet()
             ) {
            System.out.println(entry.getKey()+"--"+entry.getValue());
        }
        //4.判断
        System.out.println(students.containsKey(s1));
        System.out.println(students.isEmpty());

    }
}

总结:(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以后是尾插入

(2)TreeMap

:实现了SortedMap接口(是Map的子接口),可以对key自动排序。

package com.collection.map;

import java.util.Map;
import java.util.TreeMap;

/**
 * TreeMap的使用
 * 存储结构:红黑树
 */
public class Demo03 {
    public static void main(String[] args) {
        //新建集合
        TreeMap<Student,String> treeMap = new TreeMap<>();
        //1.添加元素
        Student s1 = new Student("赵",100);
        Student s2 = new Student("钱",101);
        Student s3 = new Student("孙",102);
        treeMap.put(s1,"北京");
        treeMap.put(s2,"上海");
        treeMap.put(s3,"深圳");
        treeMap.put(new Student("孙",102),"南京");//重写CompareTo()方法比较学号,学号一样添加失败,value覆盖
        System.out.println("元素个数:"+treeMap.size());
        System.out.println(treeMap.toString());
        //2.删除
        treeMap.remove(s3);
        System.out.println("删除之后:"+treeMap.size());
        //3.遍历
        //(1)使用keySet
        for (Student key:treeMap.keySet()
             ) {
            System.out.println(key+"--"+treeMap.get(key));
        }
        //(2)entrySet
        for (Map.Entry<Student,String> entry:treeMap.entrySet()
             ) {
            System.out.println(entry.getKey()+"--"+entry.getValue());
        }
        //4判断
        System.out.println(treeMap.containsKey(s1));

    }
}

(3)Hashtable

JDK1.0版本,线程安全,运行效率慢;不允许bull作为key或value。

(4)Properties

Hashtable的子类,要求key和value都是String。通常用于配置文件的读取。

七、Collections工具类

概念:集合工具类,定义了除了存取以外的集合常用方法。

方法:

(1)public static void reverse(List<?> list)//反转集合中元素的顺序

(2)public static void shuffle(List<?> list)//随即重置集合元素的顺序

(3)public static void sort(List list)//升序排序(元素类型必须实现Comparable接口)

package com.collection.map;

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

/**
 * 演示Collections工具类的使用
 */
public class Demo04 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(20);
        list.add(5);
        list.add(12);
        list.add(30);
        list.add(6);
        //sort排序
        System.out.println("排序之前:"+list.toString());
        Collections.sort(list);
        System.out.println("排序之后:"+list.toString());
        //binarySearch二分查找
        int i = Collections.binarySearch(list, 12);
        System.out.println(i);
        //copy复制
        List<Integer> dest = new ArrayList<>();
        for (int k = 0; k < list.size(); k++) {
            dest.add(0);
        }
        Collections.copy(dest,list);
        System.out.println(dest.toString());
        //reverse反转
        Collections.reverse(list);
        System.out.println("反转之后:"+list);
        //shuffle打乱
        Collections.shuffle(list);
        System.out.println("打乱之后:"+list);


        //补充:list转成数组
        Integer[] arr = list.toArray(new Integer[0]);
        System.out.println(arr.length);
        System.out.println(Arrays.toString(arr));

        //数组转成集合
        String[] names = {"张三","李四","王五"};
        //集合是一个受限集合,不能添加和删除
        List<String> list2 = Arrays.asList(names);
        System.out.println(list2);

        //基本类型数组转成集合时,需要修改为包装类型
        Integer[] nums = {100,200,300,400,500};
        List<Integer> list3 = Arrays.asList(nums);
        System.out.println(list3);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值