java 集合

集合框架


  • 和数组区别

    1. 数组长度固定,集合长度不固定
    2. 数组可以存储基本类型和引用类型,集合只能存储引用类型-
  • Collection接口:无下标

    • List接口:有序、有下标、元素可重复
      • ArrayList类
      • LinkedList类
      • Vector类
    • Set接口:无序、无下标、元素不重复
      • HashSet类
      • Sorted类
        • TreeSet类

Collection父接口


package jcf;

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

/**
 * Collection接口的使用
 * @author wmj
 */
public class Demo1 {
    public static void main(String[] args) {
        //创建
        Collection collection = new ArrayList();
        collection.add("haha");
        collection.add("xixi");
        collection.add("hehe");
        System.out.println(collection.size());
        System.out.println(collection);

        //删除
//        collection.remove("haha");
//        System.out.println(collection.size());
//        System.out.println(collection);

        //遍历
        //增强for
        for(Object object:collection){
            System.out.println(object);
        }
        //迭代器
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()){//有无下个元素
            String s = (String) iterator.next();//获取下个元素
            System.out.println(s);
            //collection.remove(s);CurrentModificationException并发修改异常
            iterator.remove();//删除
        }
        System.out.println(collection.size());

        //判断
        System.out.println(collection.contains("haha"));
        System.out.println(collection.isEmpty());
    }
}
package jcf;

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

public class Demo2 {
    public static void main(String[] args) {
        Collection collection = new ArrayList();
        Student s1 = new Student("haha", 1);
        Student s2 = new Student("xixi", 2);
        Student s3 = new Student("hehe", 3);
        //添加
        //加入的实际是地址
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        collection.add(s3);
        System.out.println(collection.size());
        System.out.println(collection.toString());

        //删除
        //删掉的是地址,对象还存在
        collection.remove(s1);
//        collection.remove(new Student("xixi", 2));//无效,因为这是一个新的对象
//        System.out.println(collection.size());
//        collection.clear();
//        System.out.println(collection.size());

        //遍历
        //增强for
        for (Object o:collection) {
            Student s = (Student) o;
            System.out.println(o.toString());
        }
        //迭代器
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()){
            Student s = (Student) iterator.next();
            System.out.println(s.toString());
        }

        //判断
        System.out.println(collection.contains(new Student("xixi", 2)));//false 也不是同一个对象
        System.out.println(collection.contains(s2));//true
    }
}

class Student{
    private String name;
    private int age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + 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;
    }
}

List子接口


package jcf;

import juc.A;
import juc.ListTest;

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

public class Demo3 {
    public static void main(String[] args) {
        List list = new ArrayList<>();
        //add
        list.add("haha");
        list.add("xixi");
        list.add("hehe");
        System.out.println(list.size());
        System.out.println(list.toString());

        //delete
//        list.remove("haha");
//        list.remove(0);
//        System.out.println(list.size());
//        System.out.println(list.toString());

        //traverse
//        for (int i = 0; i < list.size(); i++) {
//            System.out.println(list.get(i));
//        }
//        for (Object object : list) {
//            System.out.println(object);
//        }
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //列表迭代器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());
        }

        //judge
        System.out.println(list.contains("haha"));
        System.out.println(list.isEmpty());

        //获取下标
        System.out.println(list.indexOf("xixi"));
    }
}
package jcf;

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

public class Demo4 {

    public static void main(String[] args) {
        List list = new ArrayList();
        //添加数字类型(自动装箱)
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        System.out.println(list.size());
        System.out.println(list.toString());

        //delete
//        list.remove(20);//根据下标删除
        list.remove(new Integer(2));
        System.out.println(list.size());
        System.out.println(list.toString());

        //sublist:返回子集合   含头不含尾
        System.out.println(list.subList(1,3));
    }
}
  • ArrayList
    • 源码分析:
      • 默认容量10:private static final int DEFAULT_CAPACITY = 10;
        • 添加元素之后的默认容量是10
        • 没添加时是0
      • 存放元素的数组:transient Object[] elementData;
      • 实际元素个数:private int size;
      • 添加元素:
    • 数组结构实现,查询快,增删慢
    • jdk1.2,运行效率快,线程不安全;vector jdk1.0,运行效率慢,线程安全
package jcf;

import juc.A;

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

public class Demo5 {
    public static void main(String[] args) {

        ArrayList arrayList = new ArrayList();
        Student2 s1 = new Student2("haha", 1);
        Student2 s2 = new Student2("xixi", 2);
        Student2 s3 = new Student2("hehe", 3);

        //add
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        System.out.println(arrayList.size());
        System.out.println(arrayList.toString());

        //delete
        arrayList.remove(s2);
        arrayList.remove(new Student2("haha", 1));//删不掉 equals(this==obj)
        // 重写Student2里的equals方法就能删除了
        System.out.println(arrayList.toString());

        //traverse
        // 迭代器
        Iterator iterator = arrayList.iterator();
        while (iterator.hasNext()){
            Student2 s = (Student2) iterator.next();
            System.out.println(s.toString());
        }
        // 列表迭代器 可正序逆序输出
        ListIterator listIterator = arrayList.listIterator();
        while (listIterator.hasNext()){
            Student2 s = (Student2) listIterator.next();
            System.out.println(s.toString());
        }

        //judge
        System.out.println(arrayList.contains(new Student("xx",1)));//因为已经重写了equals方法
        System.out.println(arrayList.isEmpty());

        // query
        System.out.println(arrayList.indexOf(new Student2("hehe", 3)));
    }
}

class Student2{
    private String name;
    private int age;

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

    public Student2() {
    }

    public Student2(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 boolean equals(Object o) {
        if(this==o){
            return true;
        }
        if(o==null){
            return false;
        }
        if(o instanceof Student2){
            Student2 s = (Student2) o;
            if(this.name.equals(s.getName()) && this.age == s.getAge()){
                return true;
            }
        }
        return false;
    }

}
  • Set
package jcf;

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

public class Demo6 {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("xixi");
        set.add("haha");
        set.add("hehe");
        set.add("haha");
        System.out.println(set.size());
        System.out.println(set.toString());

        // 遍历
        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.contains("haha"));
    }
}
  • HashSet
    • 基于HashCode计算元素存放位置
    • 哈希码相同时,会调用equals进行确认,如果为true,拒绝存入
    • 存储过程
      1. 根据hashcode计算保存位置,如果为空,则直接保存,否则执行2
      2. 执行equals方法,如果返回true,则认为是重复的,否则形成链表
import java.util.HashSet;
import java.util.Iterator;

public class Demo7 {
    public static void main(String[] args) {
        HashSet<String> hashSet = new HashSet<>();
        hashSet.add("haha");
        hashSet.add("xixi");
        hashSet.add("hehe");
        hashSet.add("xixi");
        System.out.println(hashSet.size());
        System.out.println(hashSet.toString());

        hashSet.remove("xixi");
        System.out.println(hashSet.toString());

        // 遍历
        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.contains("xixi"));
    }
}
import java.util.HashSet;
import java.util.Iterator;

public class Demo8 {
    public static void main(String[] args) {
        HashSet<Person> hashSet = new HashSet<>();
        Person p1 = new Person("haha", 1);
        Person p2 = new Person("xixi", 2);
        Person p3 = new Person("hehe", 3);
        hashSet.add(p1);
        hashSet.add(p2);
        hashSet.add(p3);
        hashSet.add(p3);// 重复加不进去
        hashSet.add(new Person("xixi", 2));// 加的进去, 重写hashcode和equals方法就加不进去了
        System.out.println(hashSet.size());
        System.out.println(hashSet.toString());

        hashSet.remove(p1);
        hashSet.remove(new Person("xixi", 2));
        System.out.println(hashSet.toString());

        for(Person p: hashSet){
            System.out.println(p.toString());
        }
        Iterator<Person> iterator = hashSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

class 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 obj) {
//        // 判断是否是同一个对象
//        if (this == obj) {
//            return true;
//        }
//        if (this == null) {
//            return false;
//        }
//        if (obj instanceof Person) {
//            Person person = (Person) obj;
//            if(this.name.equals(person.getName()) && this.age == person.getAge()){
//                return true;
//            }
//        }
//
//        return false;
//    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;

        Person person = (Person) o;

        if (getAge() != person.getAge()) return false;
        return getName() != null ? getName().equals(person.getName()) : person.getName() == null;
    }

    @Override
    public int hashCode() {
        int result = getName() != null ? getName().hashCode() : 0;
        result = 31 * result + getAge();
        return result;
    }
}
  • TreeSet
    • 基于排列顺序实现元素不重复
    • 实现了SortedSet接口,对集合元素自动排序
    • 元素对象的类型必须实现Comparable接口,指定排序规则
    • 通过CompareTo方法确定是否为重复元素
package jcf;

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

public class Demo9 {
    public static void main(String[] args) {
        TreeSet<String> treeSet = new TreeSet<>();
        // 会对元素自动排序
        treeSet.add("haha");
        treeSet.add("xixi");
        treeSet.add("hehe");
        treeSet.add("haha");
        System.out.println(treeSet.size());
        System.out.println(treeSet.toString());

        treeSet.remove("hehe");
        System.out.println(treeSet.toString());

        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.contains("xixi"));
    }
}
package jcf;

import java.util.TreeSet;

public class Demo10 {
    public static void main(String[] args) {
        // 元素必须实现Comparable接口
        // compareTo()返回0就认为是重复的
        TreeSet<Person> treeSet = new TreeSet<>();
        Person person1 = new Person("haha", 1);
        Person person2 = new Person("xixi", 2);
        Person person3 = new Person("hehe", 3);
        Person person4 = new Person("haha", 0);

        treeSet.add(person1);
        treeSet.add(person2);
        treeSet.add(person3);
        treeSet.add(person4);
        System.out.println(treeSet.size());
        System.out.println(treeSet.toString());
        
        treeSet.remove(new Person("haha", 0));// 可以删除,因为已经实现了compareTo()
        
    }
}

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

    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 int compareTo(Person o) {
        int n1 = this.getName().compareTo(o.getName());
        int n2 = this.getAge() - o.getAge();
        return n1==0?n2:n1;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package jcf;

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

public class Demo11 {
    public static void main(String[] args) {
        // 创建集合时指定规则 Comparator
        TreeSet<Person> personTreeSet = 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 person1 = new Person("haha", 1);
        Person person2 = new Person("xixi", 0);
        Person person3 = new Person("hehe", 3);
        Person person4 = new Person("haha", 3);

        personTreeSet.add(person1);
        personTreeSet.add(person2);
        personTreeSet.add(person3);
        personTreeSet.add(person4);
        System.out.println(personTreeSet.toString());
    }
}
  • 使用TreeSet实现字符串按长度排序
package jcf;

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

public class Demo12 {
    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("cat");
        System.out.println(treeSet.toString());
    }
}
  • Map
    • 遍历:map.keySet();map.entrySet()(效率更高)
package jcf;

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

public class Demo13 {
    public static void main(String[] args) {
        // 存储键值对 键不可重复,值可重复 无序
        Map<String,String> map = new HashMap<>();
        map.put("cn", "中国");
        map.put("usa", "美国");
        map.put("uk", "英国");
        //map.put("uk", "国");// 会覆盖原来的
        System.out.println(map.size());
        System.out.println(map.toString());

        // 删除
//        map.remove("uk");
//        System.out.println(map.toString());

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

        // 判断
        System.out.println(map.containsKey("usa"));
        System.out.println(map.containsValue("zho"));
    }
}
  • HashMap
    • HashMap()默认构造一个具有默认初始容量16,默认加载因子0.75的hashmap(元素达到百分之75时该扩容为原来的两倍)
    • 刚创建hashmap没添加元素时,table = null ,size = 0,添加完第一个元素后就变成16
    • jdk1.8时,链表元素大于8,数组元素大于等于64时,调整为红黑树
    • jdk1.8时,链表元素少于6,调整为链表
    • jdk1.8前,链表头插,之后是尾插
package jcf;

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

public class Demo14 {
    public static void main(String[] args) {
        HashMap<Student, String> students = new HashMap<>();
        Student s1 = new Student("haha", 1);
        Student s2 = new Student("xixi", 2);
        Student s3 = new Student("hehe", 3);
        students.put(s1, "A");
        students.put(s2, "B");
        students.put(s3, "C");
//        students.put(s3, "D");// 覆盖原来的

        // 使用key的hashcode和equals作为依据
        students.put(new Student("haha", 1), "E");// 对象地址不一样,所以可以添加进去
        // 重写hashcode和equals后加入不了

        System.out.println(students.size());
        System.out.println(students.toString());

        // 删除
        students.remove(s1);
        System.out.println(students.toString());

        // 遍历
        // keyset
        for(Student key: students.keySet()){
            System.out.println(key.toString() + " " + students.get(key));
        }
        // entryset
        for(Map.Entry<Student, String> entry: students.entrySet()){
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

        // 判断
        // 重写过hashcode和equals,判断方法已经变了所以为true
        System.out.println(students.containsKey(new Student("xixi", 2)));
    }
}

class Student{
    private String name;
    private int stuNo;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;

        Student student = (Student) o;

        if (getStuNo() != student.getStuNo()) return false;
        return getName() != null ? getName().equals(student.getName()) : student.getName() == null;
    }

    @Override
    public int hashCode() {
        int result = getName() != null ? getName().hashCode() : 0;
        result = 31 * result + getStuNo();
        return result;
    }

    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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", stuNo=" + stuNo +
                '}';
    }
}
  • TreeMap
package jcf;

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

public class Demo16 {
    public static void main(String[] args) {
        // 定制比较或者在类里继承Comparable接口
        TreeMap<Student, String> students = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getStuNo() - o2.getStuNo();
            }
        });
        Student s1 = new Student("haha", 1);
        Student s2 = new Student("xixi", 2);
        Student s3 = new Student("hehe", 3);
        students.put(s1, "A");
        students.put(s2, "B");
        students.put(s3, "C");// student类需要继承Comparable接口
        students.put(new Student("xixi", 2), "D");// 可以加入
        System.out.println(students.size());
        System.out.println(students.toString());

        // 删除
        students.remove(new Student("xixi",2), "D");
        System.out.println(students.toString());

        // 遍历
        // keySet
        for(Student key:students.keySet()){
            System.out.println(students.get(key));
        }
        // entrySet
        for(Map.Entry<Student, String> entry: students.entrySet()){
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

        System.out.println(students.containsKey(new Student("haha",1)));
    }
}

class Student implements Comparable<Student>{
    private String name;
    private int stuNo;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;

        Student student = (Student) o;

        if (getStuNo() != student.getStuNo()) return false;
        return getName() != null ? getName().equals(student.getName()) : student.getName() == null;
    }

    @Override
    public int hashCode() {
        int result = getName() != null ? getName().hashCode() : 0;
        result = 31 * result + getStuNo();
        return result;
    }

    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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", stuNo=" + stuNo +
                '}';
    }


    // comparable<Student>或者在代码里强制转换
    @Override
    public int compareTo(Student o) {
        return this.stuNo - o.stuNo;
    }
}
  • Collections
posted @ 2021-03-24 21:54  _Sylvan  阅读(30)  评论(0)    收藏  举报