集合

集合

集合概念

对象的容器,实现了对对象常用的操作,类似数组功能

和数组的区别

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

Collection体系集合

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()//将此集合转换成数组
    • Iterator iterator()//返回此collection的元素上进行迭代的迭代器 实现遍历
    • boolean removeAll(Object o )// 去除两个集合的交集
    • boolean retainAll(Object o)//保留两个集合的交集

Collection接口的使用:String

package OOP.collection;

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

/**
 * @version: java version 1.8
 * @Author: 14
 *  * Collection接口的使用
 *  * 1、添加
 *  * 2、删除
 *  * 3、遍历
 *  * 4、判断
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        Collection collection = new ArrayList();
//         *  * 1、添加
        collection.add(1);
        collection.add(2);
        collection.add(3);
        System.out.println("元素个数:" + collection.size());
        System.out.println(collection);
//         *  * 2、删除
        //collection.remove(2);
        //collection.clear();
        //System.out.println("删除后个数:" + collection.size());
//         *  * 3、遍历(重点)
        //3.1 增强for
        for (Object o : collection) {
            System.out.println(o);
        }
        //3.2 迭代器(专门用来遍历集合的方式)
        //hasNext()有没有下一个元素
        //next()获取下一个元素
        //remove()删除当前元素
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            //不能使用collection删除方法
            //collection.remove(iterator.next())  ×
            //iterator.remove(); √
        }
        System.out.println(collection.size());
//         *  * 4、判断
        System.out.println(collection.contains(1));
        System.out.println(collection.isEmpty());
    }
}

Collection接口的使用:保存学生信息 (对象)

package OOP.collection;

/**
 * @version: java version 1.8
 * @Author: 14
 */
public class Student {
    private String name;
    private int age;

    public Student() {
    }

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

    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 +
                '}';
    }
    //下方ArrayList示例时重写,本例时没重写该方法
    @Override
    public boolean equals(Object obj) {
        //是不是同一个对象
        if (this == obj) return true;
        //是不是为空
        if (obj == null) return false;
        //是不是Student类型
        if (obj instanceof Student) {
            Student student = (Student) obj;
            //比较属性
            if (this.name.equals(student.getName()) && this.age == student.getAge()) {
                return true;
            }
        }
        //不满足条件 false
        return false;
    }
}
package OOP.collection;

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

/**
 * @version: java version 1.8
 * @Author: 14
 *  * Collection接口的使用:保存学生信息
 */
public class Demo {
    public static void main(String[] args) {
        //新建Collection对象
        Collection collection = new ArrayList();
        Student s1 = new Student(18,"Smith");
        Student s2 = new Student(19,"John");
        Student s3 = new Student(20,"Mike");
        //1.添加数据
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        System.out.println(collection.size());
        System.out.println(collection.toString());
        //2.删除
        //只是删除了 collection里存储的这个对象的地址
        collection.remove(s1);
        //3.遍历
        //3.1 增强for
        for (Object o : collection) {
            Student s = (Student) o;
            System.out.println(s.toString());
        }
        System.out.println("=====================");
        //3.2 迭代器:hasNext(),next(),remove();  迭代过程中不能使用collection的删除方法
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
            Student s = (Student) iterator.next();
            System.out.println(s.toString());
        }
        //4.判断  collection里存的是学生对象的地址 所以无法查询是否包含的具体内容
        System.out.println(collection.contains("Smith"));
        System.out.println(collection.contains(s2));
    }
}

List子接口

  • 特点:有序、有下标、元素可以重复
  • 方法:
    • void add(int index,0bject o)/在index位置插入对象o
    • boolean addAll(int index,Collection c)//将一个集合中的元素添加到此集合中的index位置
    • Object get(int index)//返回集合中指定位置的元素
    • List subList(int fromIndex,int toIndex)//返回fromIndex和toIndex之间的集合元素
package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @Author: 14
 *  * List接口的使用:
 *    有序、有下标、可重复
 */
public class Demo {
    public static void main(String[] args) {
        //新建List对象
        List list = new ArrayList();
        //添加
        list.add("A");
        list.add("B");
        list.add(0,"C");
        System.out.println("元素个数:" + list.size());
        System.out.println(list.toString());
        //删除
//        list.remove("B");
//        list.remove(0);
//        System.out.println("元素个数:" + list.size());
        //遍历
        //for
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        //增强for
        for (Object o : list) {
            System.out.println(o.toString());
        }
        //迭代器
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        //列表迭代器,和Iterator的区别:ListIterator 可以向前或向后遍历、添加、删除、修改元素
        ListIterator listIterator = list.listIterator();
        System.out.println("--------从前往后---------");
        while (listIterator.hasNext()) {
            System.out.println(listIterator.nextIndex()+":"+listIterator.next());
        }
        System.out.println("--------从后往前---------");
        while (listIterator.hasPrevious()) {
            System.out.println(listIterator.previousIndex()+":"+listIterator.previous());
        }
        //判断
        System.out.println(list.contains("B"));
        System.out.println(list.isEmpty());
        //获取位置
        System.out.println(list.indexOf("C"));
    }
}

List实现类

  • ArrayList(重点):

    • 数组结构实现,查询快、增删慢;

    • JDK1.2版本,运行效率快、线程不安全

    • 源码分析:

      • 默认容量:DEFAULT_CAPACITY = 10

        • 如果没有向集合中添加任何元素,容量为0,size为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) {
            ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
        }
        ->
        private static int calculateCapacity(Object[] elementData, int minCapacity) {
                if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
                    return Math.max(DEFAULT_CAPACITY, minCapacity);
                }
                return 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);
        }
        
  • Vector:

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

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

ArrayList

package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @Author: 14
 * ArrayList的使用:
 */
public class Demo {
    public static void main(String[] args) {
        //新建集合
        ArrayList arrayList = new ArrayList();
        //增
        Student s1 = new Student(30, "Andy");
        Student s2 = new Student(30, "Chris");
        Student s3 = new Student(30, "Luise");
        arrayList.add(s1);
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        System.out.println("元素个数"+arrayList.size());
        System.out.println(arrayList.toString());
        //删
//        arrayList.remove(s1);
//        //重写Student的equals方法后能够使用下面这一句删除对象
//        arrayList.remove(new Student(30,"Andy"));
//        System.out.println("元素个数"+arrayList.size());
        //遍历(重点)
        //3.1 迭代器
        System.out.println("--------迭代器----------");
        Iterator iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            Student student = (Student) iterator.next();
            System.out.println(student.toString());
        }
        //3.2 列表迭代器
        System.out.println("--------列表迭代器 正序----------");
        ListIterator listIterator = arrayList.listIterator();
        while (listIterator.hasNext()) {
            Student student = (Student) listIterator.next();
            System.out.println(student.toString());
        }
        System.out.println("--------列表迭代器 逆序----------");
        while (listIterator.hasPrevious()) {
            Student student = (Student) listIterator.previous();
            System.out.println(student.toString());
        }
        //判断
        //重写Student的equals方法后能够使用new
        System.out.println(arrayList.contains(new Student(30, "Luise")));
        System.out.println(arrayList.isEmpty());
        //查找
        //重写Student的equals方法后能够使用new
        System.out.println(arrayList.indexOf(new Student(30, "Luise")));
    }
}

Vector

package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @Author: 14
 * Vector的使用:
 */
public class Demo {
    public static void main(String[] args) {
        //新建集合
        Vector v = new Vector();
        //增
        v.add("西瓜");
        v.add("香蕉");
        v.add("菠萝");
        //删
//        v.remove(0);
//        v.remove("西瓜");
//        v.clear();
        //遍历
        //使用枚举器
        Enumeration elements = v.elements();
        while (elements.hasMoreElements()) {
            String s = (String) elements.nextElement();
            System.out.println(s);
        }
        //判断
        System.out.println(v.contains("西瓜"));
        System.out.println(v.isEmpty());
        //其他方法
        //firstElement,lastElement,ElementAt();
    }
}

LinkedList

package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @Author: 14
 * LinkedList接口的使用:
 * 存储结构:双向链表
 */
public class Demo {
    public static void main(String[] args) {
        //新建集合
        LinkedList list = new LinkedList<>();
        //增
        Student s1 = new Student(30, "Andy");
        Student s2 = new Student(30, "Chris");
        Student s3 = new Student(30, "Luise");
        list.add(s1);
        list.add(s1);
        list.add(s2);
        list.add(s3);
        System.out.println("元素个数"+list.size());
        System.out.println(list);
        //删
//        list.remove(0);
//        list.remove(new Student(30, "Andy"));
//        list.clear();
        //遍历
        //for
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        //增强for
        for (Object o : list) {
            System.out.println(o);
        }
        //迭代器
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        //ListIterator
        ListIterator listIterator = list.listIterator();
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }
        //判断
        System.out.println(list.contains(s1));
        System.out.println(list.isEmpty());

        //查找
        System.out.println(list.indexOf(s1));
    }
}

ArrayList和LinkedList的区别

不同实现结构:

泛型

  • Java泛型是JDK1.5引入的一个新特性,其本质是参数化类型,把类型作为参数传递
  • 常见形式有泛型类、泛型接口、泛型方法
  • 语法:
    • <T,...>T称为类型占用符,表示一种引用类型
  • 好处:
    • 提高代码的重用性
    • 防止类型转换异常,提高代码的安全性

泛型类

package OOP.collection;

/**
 * @version: java version 1.8
 * @Author: 14
 * 泛型类
 * 语法:类名<T>
 *     T表示一种引用类型,如编写多个,用逗号隔开
 */
public class MyGeneric<T>{
    //使用泛型T
    //1 创建变量
    T t;
    //2 添加方法
    public void show(T t){
        System.out.println(t);
    }
    //3 泛型作为方法的返回值
    public T getT(){
        return t;
    }
}

泛型接口

package OOP.collection;

/**
 * @version: java version 1.8
 * @Author: 14
 */
public class MyInterfaceImpl implements MyInterface<String> {

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

/**
 * @version: java version 1.8
 * @Author: 14
 */
public class MyInterfaceImpl2<T> implements MyInterface<T> {
    @Override
    public T server(T t) {
        System.out.println(t);
        return t;
    }
}

泛型方法

package OOP.collection;

/**
 * @version: java version 1.8
 * @Author: 14
 * 泛型方法
 * 语法:<T> 返回值类型
 */
public class MyGenericMethod {
    //泛型方法
    public <T> void method(T t) {
        System.out.println("泛型方法" + t );
    }
}

使用

package OOP.collection;

/**
 * @version: java version 1.8
 * @Author: 14
 */
public class TestGeneric {
    public static void main(String[] args) {
        //使用泛型类创建对象
        //注意:1、泛型只能使用引用类型 2、不同泛型类型对象之间不能相互赋值
        MyGeneric<Integer> myGeneric = new MyGeneric<>();
        myGeneric.t = 100;
        myGeneric.show(10000);
        Integer i = myGeneric.getT();

        //泛型接口
        MyInterfaceImpl myInterfaceImpl = new MyInterfaceImpl();
        myInterfaceImpl.server("sss");
        MyInterfaceImpl2 myInterfaceImpl2 = new MyInterfaceImpl2();
        myInterfaceImpl2.server(1000);

        //泛型方法
        MyGenericMethod myGenericMethod = new MyGenericMethod();
        myGenericMethod.method("Smith");
        myGenericMethod.method(200);
    }
}

泛型集合

  • 概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致
  • 特点
    • 编译时即可检查,而非运行时抛出异常
    • 访问时,不必类型转换(拆箱)
    • 不同泛型之间引用不能相互赋值,泛型不存在多态
package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @Author: 14
 * 泛型集合应用
 */
public class Demo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("A");
        list.add("B");
//      添加的数据与规定的泛型不一致,不能添加
//        list.add(111);
//        list.add(222);
        ArrayList<Student> studentArrayList = new ArrayList<Student>();
        Student s1 = new Student(19, "aa");
        Student s2 = new Student(20, "bb");
        studentArrayList.add(s1);
        studentArrayList.add(s2);
        
        //泛型不一样,不能赋值
//        list = studentArrayList;
    }
}

Set子接口

  • 特点:无序、无下标、元素不可以重复
package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:测试Set接口使用
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        Set<String> set = new HashSet<>();

        //增
        set.add("xiaomi");
        set.add("huawei");
        set.add("apple");
        System.out.println("set.Size: " + set.size());
        System.out.println(set.toString());
        
        //删
//        set.remove("xiaomi");

        //遍历(重点)
        //增强for
        for (String s : set) {
            System.out.println(s);
        }
        //迭代器
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        //判断
        System.out.println(set.isEmpty());
        System.out.println(set.contains("xiaomi"));
    }
}

Set实现类

HashSet

  • 基于HashCode计算元素存放位置
  • 当存入元素的哈希码相同时,会调用equals进行确认,如果结果为true,则拒绝后者存入
package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:HashSet集合的使用
 *              存储结构:哈希表(数组+链表+红黑树)
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        HashSet<String> hashset = new HashSet<>();

        //增
        hashset.add("xiaomi");
        hashset.add("huawei");
        hashset.add("apple");
        //hashset.add("apple");不会重复添加
        System.out.println("Size: " + hashset.size());
        System.out.println(hashset.toString());

        //删
//        hashset.remove("xiaomi");

        //遍历(重点)
        //增强for
        for (String s : hashset) {
            System.out.println(s);
        }
        //迭代器
        Iterator<String> iterator = hashset.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        //判断
        System.out.println(hashset.isEmpty());
        System.out.println(hashset.contains("xiaomi"));
    }
}

HashSet集合的使用

package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:HashSet集合的使用
 *              存储结构:哈希表(数组+链表+红黑树)
 *              存储过程:(重复依据)
 *              1、根据hashcode计算保存位置,若此位置为空,直接保存,否则执行第二步
 *              2、再执行equals方法,如果equals方法为true,则认为是重复,否则,形成链表
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        HashSet<Student> hashset = new HashSet<>();

        //增
        Student s1 = new Student(18,"aaa");
        Student s2 = new Student(19,"bbb");
        Student s3 = new Student(20,"ccc");
        hashset.add(s1);
        hashset.add(s2);
        hashset.add(s3);
        //重写了hashcode计算方法和equals方法,使得能直接new一个相同的加进去
        hashset.add(new Student(18,"aaa"));
        System.out.println("Size: " + hashset.size());
        System.out.println(hashset.toString());

        //删
//        hashset.remove("xiaomi");

        //遍历(重点)
        //增强for
        for (Student s : hashset) {
            System.out.println(s);
        }
        //迭代器
        Iterator<Student> iterator = hashset.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        //判断
        System.out.println(hashset.isEmpty());
        System.out.println(hashset.contains(s1));
        System.out.println(hashset.contains(new Student(18,"aaa")));
    }
}

TreeSet

  • 基于排列顺序实现元素不重复
  • 实现了SortedSet接口,对集合元素自动排序
  • 元素对象的类型必须实现Comparable接口,指定排序规则
  • 通过CompareTo方法确定是否为重复元素

传入基本类型

package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:TreeSet集合的使用
 *              存储结构:红黑树
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        TreeSet<String> treeSet = new TreeSet<>();

        //增
        treeSet.add("aaa");
        treeSet.add("bbb");
        treeSet.add("ccc");
        System.out.println("Size: " + treeSet.size());
        System.out.println(treeSet.toString());

        //删
//        treeSet.remove("aaa");
        //遍历(重点)
        //增强for
        for (String s : treeSet) {
            System.out.println(s);
        }
        //迭代器
        Iterator<String> iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        //判断
        System.out.println(treeSet.isEmpty());
        System.out.println(treeSet.contains("aaa"));
    }
}

传入对象

package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:TreeSet集合的使用
 *              存储结构:红黑树
 *              要求:元素必须实现Comparable接口,compareTo()方法返回值为0,认为是重复元素
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        TreeSet<Student> treeSet = new TreeSet<>();

        //增
        Student s1 = new Student(18,"aaa");
        Student s2 = new Student(19,"bbb");
        Student s3 = new Student(20,"ccc");
        Student s4 = new Student(21,"ccc");
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);

        System.out.println("Size: " + treeSet.size());
        System.out.println(treeSet);

        //删
//        treeSet.remove(s1);
//        treeSet.remove(new Student(18,"aaa"));

        //遍历(重点)
        //增强for
        for (Student s : treeSet) {
            System.out.println(s);
        }
        //迭代器
        Iterator<Student> iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        //判断
        System.out.println(treeSet.isEmpty());
        System.out.println(treeSet.contains(s1));
        System.out.println(treeSet.contains(new Student(18,"aaa")));
    }
}

使用Comparator

package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:TreeSet集合的使用
 *              Comparator:实现定制比较(比较器)
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int i = o1.getAge() - o2.getAge();
                int j = o1.getName().compareTo(o2.getName());
                return i == 0 ? j : i;
            }
        });

        //增
        Student s1 = new Student(18,"aaa");
        Student s2 = new Student(19,"bbb");
        Student s3 = new Student(20,"ccc");
        Student s4 = new Student(21,"ccc");
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);

        System.out.println("Size: " + treeSet.size());
        System.out.println(treeSet);

        //删
//        treeSet.remove(s1);
//        treeSet.remove(new Student(18,"aaa"));

        //遍历(重点)
        //增强for
        for (Student s : treeSet) {
            System.out.println(s);
        }
        //迭代器
        Iterator<Student> iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        //判断
        System.out.println(treeSet.isEmpty());
        System.out.println(treeSet.contains(s1));
        System.out.println(treeSet.contains(new Student(18,"aaa")));
    }
}
package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:TreeSet集合的使用
 *              Comparator:实现定制比较(比较器)
 *              实现 按照字符串长度排序
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int length = o1.length() - o2.length();
                int compare = o1.compareTo(o2);
                return length == 0 ? compare : length;
            }
        });

        //增
        treeSet.add("helloworld");
        treeSet.add("pingguo");
        treeSet.add("lisi");
        treeSet.add("wangwu");
        treeSet.add("cat");
        treeSet.add("dog");
        treeSet.add("nanjing");
        treeSet.add("guilin");
        System.out.println(treeSet);
    }
}

Map集合

特点:

  • 用于存储任意键值对(Key-Value)
  • 无序,无下标
  • 键不可重复,值可重复
package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:Map集合的使用
 *              entry:映射对 键值对
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        Map<String,String> map = new HashMap<>();

        //增
        map.put("cn","中国");
        map.put("uk","英国");
        map.put("us","美国");
        System.out.println("size:" + map.size());
        System.out.println(map);

        //删
//        map.remove("uk");

        //遍历
        //使用keySet()
        System.out.println("-------------keySet----------");
        Set<String> strings = map.keySet();
        for (String key : strings) {
            System.out.println("key:" + key + " value:" + map.get(key));
        }
        //使用entrySet()
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
            System.out.println(entry);
        }

        //判断
        System.out.println(map.containsKey("cn"));
        System.out.println(map.containsValue("日本"));
    }
}

HashMap(重点)

线程不安全,运行效率快,允许用nlll作为key或value

package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:HashMap集合的使用
 *              存储结构:哈希表(数组+链表+红黑树)
 *              使用Key的hashcode和equals判断重复
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        HashMap<Person, String> personStringHashMap = new HashMap<>();

        //增
        Person wukong = new Person("wukong", 600);
        Person bajie = new Person("bajie", 600);
        Person shashidi = new Person("shashidi", 600);
        personStringHashMap.put(wukong, "花果山");
        personStringHashMap.put(bajie,"高老庄");
        personStringHashMap.put(shashidi,"流沙河");
        System.out.println("size:" + personStringHashMap.size());
        System.out.println(personStringHashMap);

        //删
//        personStringHashMap.remove(wukong);

        //遍历
        //使用keySet()
        System.out.println("-------------keySet----------");
        Set<Person> strings = personStringHashMap.keySet();
        for (Person key : strings) {
            System.out.println("key:" + key + " value:" + personStringHashMap.get(key));
        }
        //使用entrySet()
        Set<Map.Entry<Person, String>> entries = personStringHashMap.entrySet();
        for (Map.Entry<Person, String> entry : entries) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
            System.out.println(entry);
        }

        //判断
        System.out.println(personStringHashMap.containsKey(wukong));
        System.out.println(personStringHashMap.containsValue("日本"));
    }
}

总结:

  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 和 Properties

Hashtable:线程安全,运行效率慢,不允许用null作为key或value

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

TreeMap

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

package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:TreeMap集合的使用
 *              存储结构:红黑树
 *              要求元素要实现Comparable接口  或者  定制比较
 *TreeMap<Person, String> treeMap = new TreeMap<>(new Comparator<Person>() {
 *           @Override
 *           public int compare(Person o1, Person o2) {
 *               //修改比较规则
 *           }
 *       });
 */
public class Demo {
    public static void main(String[] args) {
        //创建集合
        TreeMap<Person, String> treeMap = new TreeMap<>();

        //增  要求元素要实现Comparable接口
        Person wukong = new Person("wukong", 600);
        Person bajie = new Person("bajie", 600);
        Person shashidi = new Person("shashidi", 600);
        treeMap.put(wukong, "花果山");
        treeMap.put(bajie,"高老庄");
        treeMap.put(shashidi,"流沙河");
        System.out.println("size:" + treeMap.size());
        System.out.println(treeMap);

        //删
//        personStringHashMap.remove(wukong);

        //遍历
        //使用keySet()
        System.out.println("-------------keySet----------");
        Set<Person> strings = treeMap.keySet();
        for (Person key : strings) {
            System.out.println("key:" + key + " value:" + treeMap.get(key));
        }
        //使用entrySet()
        Set<Map.Entry<Person, String>> entries = treeMap.entrySet();
        for (Map.Entry<Person, String> entry : entries) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
            System.out.println(entry);
        }

        //判断
        System.out.println(treeMap.containsKey(wukong));
        System.out.println(treeMap.containsValue("日本"));
    }
}

Colletions工具类

  • 集合工具类,定义了除了存取以外的集合常用方法
  • 方法:
    • public static void reverse(List<?> list)//反转集合中元素的顺序
    • public static void shuffle(List<?> list)//随机重置集合元素的顺序
    • public static void sort(List list)//升序排序(元素类型必须实现Comparable接口)
package OOP.collection;

import java.util.*;

/**
 * @version: java version 1.8
 * @author: 14
 * @description:Colletions工具类的使用
 */
public class Demo {
    public static void main(String[] args) {
        //创建
        List<Integer> list = new ArrayList<>();
        list.add(49);
        list.add(45);
        list.add(98);
        list.add(37);
        list.add(16);

        //sort排序
        System.out.println("排序前:" + list);
        Collections.sort(list);
        System.out.println("排序后:" + list);

        //binarySearch
        System.out.println(Collections.binarySearch(list, 49));

        //copy 复制  copy需要两个集合大小相同 所以先for
        List<Integer> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            list1.add(list.get(i));
        }
        Collections.copy(list1,list);
        System.out.println(list1);

        //reverse反转
        Collections.reverse(list);
        System.out.println(list);

        //shuffle 打乱
        Collections.shuffle(list);
        System.out.println(list);

        //补充
        //list  ->数组
        Integer[] array = list.toArray(new Integer[list.size()]);
        System.out.println(array.length);
        System.out.println(Arrays.toString(array));
        //数组 -> 集合
        String[] names = {"wukong","wujing","wuneng"};
        //这是一个受限集合,不能添加和删除
        List<String> list2 = Arrays.asList(names);
        System.out.println(list2);

        //基本数据类型的数组转集合有问题,要变成包装类型再转换
        Integer[] nums = {1,2,3,4,5,6,7,8,9};
        List<Integer> list3 = Arrays.asList(nums);


    }
}
posted @ 2024-07-10 20:46  十四2001  阅读(1)  评论(0编辑  收藏  举报