集合框架

集合框架

  • 集合的概念:对象的容器,实现了对对象进行操作的常用方法。可实现数组的功能。

  • 和数组的区别:

    • 数组长度固定,集合长度不固定。

    • 数组可以存储基本类型和引用类型,集合只能存储引用类型。

  • 位置:java.util.*

Collection体系集合

  • Collection:该体系结构的根接口,代表一组对象,称为“集合”。
    • List:接口特点:有序,有下标,元素可重复。
      • ClassArrayList、ClassLinkedList、ClassVector
    • Set::接口特点:无序、无下标、元素不能重复。
      • ClassHashSet、InterfaceSortedSet(classTreeSet)

Collection父接口

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

  • 方法:

    • boolean add(Object obj)//添加一个对象。

    • boolean addAll(Collection)//将一个集合中所有对象添加到此集合中。

    • void clear()//清空此集合中所有对象。

    • boolean contains(Object o)//检查此集合中是否包含o对象。

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

    • boolean isEmpty()//判断此集合是否为空。

    • boolean remove(Object o)//在此集合中移除o对象。

    • int size()//返回此集合中的元素个数。

    • Object[] toArray()//将此集合转换成数组。

package gather;

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());//3
        System.out.println(collection);//[苹果, 西瓜, 榴莲]
//        // 2.删除元素
//        collection.remove("榴莲");
//        System.out.println("删除之后:"+collection.size());//删除之后:2
        // 3.遍历元素(重点)
        //第一种 使用增强for
        for (Object object:collection){
            System.out.println(object);//苹果 西瓜 榴莲
        }
        //第二种 使用迭代器(迭代器专门用来遍历集合的一种方式)
        //hasNext():有没有下一个元素
        //next():获取下一个元素
        //remove():删除当前元素
        Iterator it=collection.iterator();
        while (it.hasNext()){
            String s=(String)it.next();
            System.out.println(s);//苹果 西瓜 榴莲
            //不能使用collection删除方法
           // collection.remove(s);//并发修改异常
           // it.remove();
        }
        System.out.println("元素个数:"+collection.size());//元素个数:0
        // * 4.判断
        System.out.println(collection.contains("西瓜"));//true
    }
}  

List接口与实现类

  • 特点:有序,有下标,元素可重复。

  • 方法:

    • void add(int index,Object o)//在index位置插入对象o

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

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

    • List subList(int formIndex,int toIndex)//返回formIndex和toIndex之间的元素

package gather;

import javax.swing.text.html.HTMLDocument;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.ListIterator;

/**
 * List接口的使用
 * 特点:1.有序,有下标2.可重复*/
public class Demo02 {
    public static void main(String[] args) {
        //先创建集合对象
        List list=new ArrayList<>();
        //1.添加元素
        list.add("苹果");
        list.add("小米");
        list.add("华为");
        System.out.println("元素个数:"+list.size());//元素个数:3
        System.out.println(list.toString());//[苹果, 小米, 华为]
        //2.删除元素
//        list.remove(0);
//        System.out.println("删除之后:"+list.size());//删除之后:2
//        System.out.println(list.toString());//[小米, 华为]
        //3.遍历
        //第一种方式 for
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));   //   苹果 小米 华为
        }
        //第二种使用增强FOR
        for(Object object:list){
            System.out.println(object);//苹果 小米 华为
        }
        //第三种使用迭代器
       Iterator it= list.iterator();
        while (it.hasNext()){
            System.out.println(it.next());//苹果 小米 华为
        }
        //第四种使用列表迭代器 和Iterator区别,listIterator可以向前或向后遍历,添加删除修改元素
        ListIterator lit=list.listIterator();
        while(lit.hasNext()){
            System.out.println(list.nextIndex()+":"+lit.next());//从前往后遍历
        }
        while(lit.hasPrevious()){
            System.out.println(list.previousIndex()+":"+lit.previous());//从后往前遍历
        }
        //判断
        System.out.println(list.contains("苹果"));
        System.out.println(list.isEmpty());
        //获取位置
        System.out.println(list.indexOf("华为"));
        //补充方法:subList返回子集合
        List subList=list.sublist(1,3);
         System.out.println(list.toString());
    }
}

List实现类

  1. ArrayList【重点】:
  • 数组结构实现,查询、增删慢;

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

    package gather;
    
    import oop.demo01.demo07.Student;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.ListIterator;
    
    /**
     * ArrayList的使用
     * 存储结构:数组,查找遍历的速度快,增删慢*/
    public class Demo03 {
        public static void main(String[] args) {
            ArrayList arrayList=new ArrayList<>();
            //1.添加元素
            Student s1=new Student("刘德华",20);
            arrayList.add(s1);
            System.out.println("元素个数:"+arrayList.size());
            System.out.println(arrayList.toString());
            //2.删除元素
            arrayList.remove(new gather.Student("刘德华",20));
            System.out.println("删除之后:"+arrayList.size());
            //3.遍历元素
            //使用迭代器
            Iterator it=arrayList.iterator();
            while (it.hasNext()){
                gather.Student s=(gather.Student) it.next();
                System.out.println(s.toString());
            }
            //列表迭代器
            ListIterator lit= arrayList.listIterator();
            while (lit.hasNext()){
                gather.Student s=(gather.Student) lit.next();
                System.out.println(s.toString());
            }
            while (lit.hasPrevious()){
                gather.Student s=(gather.Student) lit.previous();
                System.out.println(s.toString());
            }
            //4.判断
            System.out.println(arrayList.contains(s1));
            System.out.println(arrayList.isEmpty());
            //5.查找
            System.out.println(arrayList.indexOf(new gather.Student("刘德华",20)));
        }
    }
    
    package gather;
    
    public class Student {
        private String name;
        private int age;
    
        public Student() {
    
        }
    
        public Student(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge(int age) {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "Student[name=" + name + ",age=" + age + "]";
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (obj instanceof Student) {
                Student s=(Student) obj;
                if (this.name.equals(s.getName())&&this.age==s.getAge(1)){
                    return true;
                }
            }
            return false;
        }
    }
    

源码分析:

  • 默认容量:DATE_CAPCITY=10;

    注意:如果没有向集合中添加任何元素时,容量0

  • 存放元素:elementDate;

  • 实际元素个数:size;

  • 添加元素:add()

    prviate boolean add(E e){
        ensureCapacityInternal(size+1);
        elementDate(size++)==e;
        return true;
    }
    private void ensureCapacityInternal(int minCapacity){
        if(elementDate==DEFAULCAPACITY_EMPTY_ELLEMNTDATA){
            minCapacity=Math.max(DEFAUL_CAPAVITY,minCapacity);
    }
        ensureExplicitCapacity(minCapacity);
    
  1. Vector:
  • 数组结构实现,查询快、增删慢;

  • JDK1.0版本,运行效率慢、线程安全。

    package gather;
    import javax.xml.bind.Element;
    import java.util.Enumeration;
    import  java.util.Vector;
    public class Demo03 {
        public static void main(String[] args) {
            //创建集合
            Vector vector=new Vector();
            //1.添加元素
            vector.add("桂圆");
            System.out.println("元素个数:"+vector.size());//元素个数:1
            //2.删除
    //        vector.remove(0);
    //        vector.clear();
            //3.遍历
            //使用枚举器
            Enumeration en=vector.elements();
            while (en.hasMoreElements()){
                String o=(String)en.nextElement();
                System.out.println(o);//桂圆
            }
            //判断
            System.out.println(vector.contains("西瓜"));//false
            System.out.println(vector.isEmpty());//false
            //vector其他方法
            //firstetElement,lastElement, ElementAt()
        }
    }
    
  1. LinkedList:
  • 链表结构实现,增删快,查询慢。

    package gather;
    import javax.swing.text.html.HTMLDocument;
    import java.util.LinkedList;
    import java.util.Iterator;
    import java.util.ListIterator;
    
    /**
     * LingkList的使用
     * 存储结构:双向链表
     * */
    public class Demo04 {
        public static void main(String[] args) {
            //创建集合
            LinkedList linkedList=new LinkedList<>();
            Student s1=new Student("刘德华",20);
            //添加元素
            linkedList.add(s1);
            System.out.println(linkedList.toString());//[Student[name=刘德华,age=20]]
            System.out.println("元素个数:"+linkedList.size());//元素个数:1
            //删除元素
    //        linkedList.remove(new Student("刘德华",20));//删除之后:1
    //        System.out.println("删除之后:"+linkedList.size());
    //        linkedList.clear();
            //遍历
            //1.for遍历
            for (int i = 0; i < linkedList.size(); i++) {
                System.out.println(linkedList.get(i));//Student[name=刘德华,age=20]
            }
            //2.增强for
            for (Object object:linkedList){
                Student s=(Student)object;
                System.out.println(s.toString());//Student[name=刘德华,age=20]
            }
            //3.迭代器
          Iterator it=linkedList.iterator();
            while (it.hasNext()){
                Student s=(Student)it.next();
                System.out.println(s.toString());//Student[name=刘德华,age=20]
            }
            ListIterator lit= linkedList.listIterator();
            while(lit.hasNext()){
                Student s=(Student)lit.next();
                System.out.println(s.toString());//Student[name=刘德华,age=20]
            }
            //判段
            System.out.println(linkedList.contains(s1));//true
            System.out.println(linkedList.toString());//[Student[name=刘德华,age=20]]
            //获取
            System.out.println(linkedList.indexOf(s1));//0
        }
    }
    

ArrayList与LinkedList区别:

  • ArrayList:必须开辟连续空间,查询快,增删慢。
  • LinkedList:无须开辟连续空间,查询慢,增删快。

Set接口与实现类

Set子接口

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

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

    package gather;
    
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    
    /**
     *测试SET接口使用
     * */
    public class Demo08 {
        public static void main(String[] args) {
            //创建集合
            Set<String> set=new HashSet<>();
            //1.添加数据
            set.add("苹果");
            set.add("华为");
            System.out.println("数据个数:"+set.size());//数据个数:2
            System.out.println(set.toString());//[苹果, 华为]
            //2.删除数据
    //        set.remove("华为");
    //        System.out.println(set.toString());//[苹果]
            //3.遍历
            //3.1使用增强for
            for (String string:set){
                System.out.println(string);//苹果 华为
            }
            //3.2使用迭代器
            Iterator<String> it= set.iterator();
            while (it.hasNext()){
                System.out.println(it.next());////苹果 华为
                //4.判断
                System.out.println(set.contains("华为"));//true
                System.out.println(set.isEmpty());
            }
        }
    }
    

set实现类:HashSet、TreeSet

HashSet【重点】:

  • 基于hashCode实现元素不重复。

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

package gather;

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

/**HashSet集合使用
 * 存储结构:哈希表(数组+链表+红黑树)
 */
public class Demo09 {
    public static void main(String[] args) {
        //新建集合
        HashSet<String> hashSet=new HashSet<>();
        //1.添加元素
        hashSet.add("张三");
        hashSet.add("李四");
        hashSet.add("王五");
        hashSet.add("赵六");
        hashSet.add("赵六");
        System.out.println("元素个数:"+hashSet.size());//元素个数:4
        System.out.println(hashSet.toString());//[李四, 张三, 王五, 赵六]  无序,不重复
        //2.删除数据
//        hashSet.remove("张三");
//        System.out.println("删除之后:"+hashSet.size());//删除之后:3
        //3.遍历
        //3.1增强for
        for (String string:hashSet){
            System.out.println(string);//李四 张三 王五 赵六
        }
        //3.2使用迭代器
        Iterator<String> it=hashSet.iterator();
        while (it.hasNext()){
            System.out.println(it.next());//李四 张三 王五 赵六
        }
        //4.判断
        System.out.println(hashSet.contains("王五"));//true
        System.out.println(hashSet.isEmpty());//false
    }
}

HashSet存储方式:

package gather;

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

/**存储过程
 * 1.根据HashCode计算保存的位置,如果位置为空,则直接保存,如果不为空执行第二步
 * 2.再执行equals方法,如果equals方法为true,则认为是重复,否则,形成链表
 * */
public class Demo10 {
    public static void main(String[] args) {
        //创建集合
        HashSet<Person> people=new HashSet<>();
        //1.添加数据
        Person p1=new Person("张三",20);
        Person p2=new Person("李四",22);
        Person p3=new Person("王五",24);
        people.add(p1);
        people.add(p2);
        people.add(p3);
        people.add(new Person("张三",20));//也可以用此方式添加数据
        System.out.println("元素个数:"+people.size());//元素个数:3
        System.out.println(people.toString());//[Person [ name=王五,age+24], Person [ name=李四,age+22], Person [ name=张三,age+20]]
        //2.删除操作
//        people.remove(p1);
//        System.out.println("删除之后:"+people.size());//删除之后:2
//        people.remove(new Person("张三",20));//也可用此方法进行删除操作
        //3.遍历
        //3.1增强for
        for (Person person:people){
            System.out.println(person.toString());//[Person [ name=王五,age+24], Person [ name=李四,age+22], Person [ name=张三,age+20]]
        }
        //3.2迭代器
        Iterator<Person> it=people.iterator();
        while (it.hasNext()){
            System.out.println(it.next());//[Person [ name=王五,age+24], Person [ name=李四,age+22], Person [ name=张三,age+20]]
        }
        //4.判断
        System.out.println(people.contains(p1));//true
        System.out.println(people.isEmpty());//false
    }
}
package gather;

public class Person {
    protected String name;
    private  int age;

    public Person(String name,int age) {
        super();
        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 (obj==null){
            return false;
        }
        if (obj instanceof  Person){
            Person p=(Person) obj;
            if (this.name.equals(p.getName())&&this.age==p.getAge()){
    return true;
            }
        }
        return false;
    }
}

HashSet补充:

  • 用质数,减少散列冲突
  • 提高执行效率 31*i=(i<<5)-i

TreeSet:

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

import javax.swing.text.html.HTMLDocument;
import java.util.TreeSet;
import java.util.Iterator;

/**TreeSet的使用
 * 存储结构:红黑树
 */
public class Demo11 {
    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());//元素个数:3
        System.out.println(treeSet.toString());//[abc, hello, xyz]
        //2.删除元素
//        treeSet.remove("xyz");
//        System.out.println("删除之后:"+treeSet.size());//删除之后:2
        //3.遍历
        //3.1使用增强for
        for (String string:treeSet){
            System.out.println(string);// abc hello xyz
        }
        //3.2使用迭代器
        Iterator<String> it=treeSet.iterator();
        while (it.hasNext()){
            System.out.println(it.next());// abc hello xyz
        }
        //4.判断
        System.out.println(treeSet.contains("abc"));//true
    }
}

示例2:使用接口Comparable接口

package gather;

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

/**使用TreeSet保存数据
 * 使用红黑树
 * 要求:元素必须实现Comparable接口,CompareTo()方法返回值为0,认为时重复元素
 */
public class Demo12 {
    public static void main(String[] args) {
        //创建集合
        TreeSet<Person> people=new TreeSet<>();
        //1.添加元素
        Person p1=new Person("张三",20);
        Person p2=new Person("李四",22);
        Person p3=new Person("王五",24);
        people.add(p1);
        people.add(p2);
        people.add(p3);
        System.out.println("元素个数:"+people.size());//元素个数:3
        System.out.println(people.toString());//[Person [ name=张三,age+20], Person [ name=李四,age+22], Person [ name=王五,age+24]]
        //2.删除元素
//        people.remove(p1);
//        System.out.println(people.size());//2
//        people.remove(new Person("张三",20));
        //3.遍历
        //3.1增强for
        for (Person person:people){
            System.out.println(person.toString());//Person [ name=张三,age+20], Person [ name=李四,age+22], Person [ name=王五,age+24]
        }
        //3.2使用迭代器
        Iterator<Person> it=people.iterator();
        while(it.hasNext()){
            System.out.println(it.next());////Person [ name=张三,age+20], Person [ name=李四,age+22], Person [ name=王五,age+24]
        }
        //4.判断
        System.out.println(people.contains(p1));//true
    }
}
package gather;

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

    public Person(String name,int age) {
        super();
        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 (obj==null){
            return false;
        }
        if (obj instanceof  Person){
            Person p=(Person) obj;
            if (this.name.equals(p.getName())&&this.age==p.getAge()){
    return true;
            }
        }
        return false;
    }
//先按姓名比,再按年龄比
    @Override
    public int compareTo(Person o) {
        int n1=this.getName().compareTo(o.getName());
        int n2=this.age-o.getAge();
        return n1==0?n2:n1;
    }
}

示例3:使用接口Comparator:实现定制比较(比较器)

public class Demo12 {
    public static void main(String[] args) {
        TreeSet<Person> people=new TreeSet<>(new Comparator<Person>(){
            @Override
            public int compare(Person o1,Person o2){
                int n1=getAge()-o2.getAge();
                int n2=o1.getAge().compareTo(o2.getName());
                return n1==0?n2:n1;
            }
        });
         Person p1=new Person("张三",20);
        Person p2=new Person("李四",22);
        Person p3=new Person("王五",24);
        people.add(p1);
        people.add(p2);
        people.add(p3);
        System.out.println(people.toString());
    }
}
package gather;

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

/**要求:使用TreeSet集合实现字符串按照长度进行排序
 * helloword zhang wangwu lisi 按长度从小到大,长度一样按照字符表顺序
 */
public class Demo13 {
    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("helloword");
        treeSet.add("pingguo");
        treeSet.add("lisi");
        treeSet.add("xian");
        treeSet.add("zhangsan");
        System.out.println(treeSet.toString());//[lisi, xian, pingguo, zhangsan, helloword]
    }
}

Map接口与实现类

Map interface接口包括以下两类 其特点:

  • 用于存储任意键值对(Key-Value)
  • 键:无序、我i下表、不允许重复。(唯一)
  • 值:无序、无下标、允许重复。
  • HashMap Class

  • SortedMap interface

    • TreeMapClass

Map父接口

  • 特点:存储一对数据(Key-Value),无序、无下标,键不可重复,值可重复。

  • 方法:

    • V put(K key,V vaule)//将对象存入到集合中,关联键值。key重复则覆盖原值。

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

    • Set//返回所有Key.。

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

    • Set<Map.Entry<k,v>>//键值匹配的Set集合。

    package gather;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    /**Map接口的使用
     * 特点:1.存储键值对;2.键不能重复,值可以重复;3.无序
     */
    public class Demo14 {
        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.toString());//{usa=美国, uk=英国, cn=中国}
            System.out.println("元素个数:"+map.size());//元素个数:3
            //2.删除
    //        map.remove("usa");
    //        System.out.println("删除之后:"+map.size());//删除之后:2
            //3.遍历
            //3.1使用KeySet();
            //Set<String> keySet=map.keySet();
            for (String key:map.keySet()){
                System.out.println(key+"-----"+map.get(key));//usa-----美国 uk-----英国 cn-----中国
            }
            //3.2使用entrySet()
            Set<Map.Entry<String,String>> entries=map.entrySet();
            for (Map.Entry<String,String> entry:entries){
                System.out.println(entry.getKey()+"-----"+entry.getValue());//usa-----美国 uk-----英国 cn-----中国
            }
            //判断
            System.out.println(map.containsKey("cn"));//true
        }
    }

HashMap使用

  • JDK1.2版本,线程不安全,运行效率快允许null,作为key或时value.

    package gather;
    
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    
    /** HashMap集合的使用
     * 存储结构:哈希表(数组+链表+红黑树)
     * 使用key可hashcode和equals作为重复
     */
    public class Demo15 {
        public static void main(String[] args) {
            //创建集合
    HashMap<Student,String> students=new HashMap<Student,String>();
    //1.添加元素
            Student s1=new Student("孙悟空",100);
            Student s2=new Student("猪八戒",99);
            Student s3=new Student("沙和尚",98);
            students.put(s1,"北京");
            students.put(s2,"上海");
            students.put(s3,"广州");
            System.out.println("元素个数:"+students.size());//元素个数:3
            System.out.println(students.toString());//{Student[name=沙和尚,age=98]=广州, Student[name=猪八戒,age=99]=上海, Student[name=孙悟空,age=100]=北京}
            //2.删除
    //        students.remove(s1);
    //        System.out.println("删除之后:"+students.size());//删除之后:2
            //3.遍历
            //3.1使用keySet();
            for(Student key:students.keySet()){
                System.out.println(key.toString()+"====="+students.get(key));//Student[name=沙和尚,age=98]=====广州 Student[name=猪八戒,age=99]=====上海 Student[name=孙悟空,age=100]=====北京
            }
            //3.2使用entrySet();
            for (Map.Entry<Student,String>entry:students.entrySet()){
                System.out.println(entry.getKey()+"----"+entry.getValue());//Student[name=沙和尚,age=98]----广州 Student[name=猪八戒,age=99]----上海 Student[name=孙悟空,age=100]----北京
            }
            //4.判断
            System.out.println(students.containsKey(s1));//true
            System.out.println(students.containsValue("杭州"));//false
    
        }
    }
    
    package gather;
    
    public class Student {
        private String name;
        private int stuNo;
    
        public Student() {
    
        }
    
        public Student(String name, int stuNo) {
            super();
            this.name = name;
            this.stuNo = stuNo;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getStuNo(int stuNo) {
            return stuNo;
        }
    
        public void setstuNo(int stuNo) {
            this.stuNo = stuNo;
        }
        public int getStuNo(){
            return stuNo;
        }
    
        @Override
        public String toString() {
            return "Student[name=" + name + ",age=" + stuNo + "]";
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (obj instanceof Student) {
                Student s=(Student) obj;
                if (this.name.equals(s.getName())&&this.stuNo==s.getStuNo()){
                    return true;
                }
            }
            return false;
        }
    }
    

    总结:

    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自动排序。
package gather;

import sun.reflect.generics.tree.Tree;

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

/** TreeMap集合的使用
 * 存储结构:哈希表(数组+链表+红黑树)
*/
public class Demo16 {
    public static void main(String[] args) {
        //创建集合
        TreeMap<Student,String> treeMap=new TreeMap<Student,String>();
        //1.添加元素
        Student s1=new Student("孙悟空",100);
        Student s2=new Student("猪八戒",99);
        Student s3=new Student("沙和尚",98);
        treeMap.put(s1,"北京");
        treeMap.put(s2,"上海");
        treeMap.put(s3,"深圳");
        System.out.println("元素个数:"+treeMap.size());//元素个数:3
        System.out.println(treeMap.toString());//{Student[name=沙和尚,age=98]=深圳, Student[name=猪八戒,age=99]=上海, Student[name=孙悟空,age=100]=北京}
        //2.删除元素
//        treeMap.remove(s3);
//        System.out.println("删除之后:"+treeMap.size());//删除之后:2
        //3.遍历
        //3.1使用KeySet
        for (Student key:treeMap.keySet()){
            System.out.println(key+"-----"+treeMap.get(key));//Student[name=沙和尚,age=98]-----深圳 Student[name=猪八戒,age=99]-----上海 Student[name=孙悟空,age=100]-----北京
        }
        //3.2使用entrySet
        for (Map.Entry<Student,String>entry:treeMap.entrySet()){
            System.out.println(entry.getKey()+"-----"+entry.getValue());//Student[name=沙和尚,age=98]-----深圳 Student[name=猪八戒,age=99]-----上海 Student[name=孙悟空,age=100]-----北京
        //4.判断
            System.out.println(treeMap.containsKey(s1));//true
            System.out.println(treeMap.containsValue("沙和尚"));//false
        }
    }
}
package gather;

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

    public Student() {

    }

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

    public String getName() {
        return name;
    }

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

    public int getStuNo(int stuNo) {
        return stuNo;
    }

    public void setstuNo(int stuNo) {
        this.stuNo = stuNo;
    }
    public int getStuNo(){
        return stuNo;
    }

    @Override
    public String toString() {
        return "Student[name=" + name + ",age=" + stuNo + "]";
    }

    @Override
    public int compareTo(Student o) {
        int n2=this.stuNo-o.getStuNo();
        return n2;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (obj instanceof Student) {
            Student s=(Student) obj;
            if (this.name.equals(s.getName())&&this.stuNo==s.getStuNo()){
                return true;
            }
        }
        return false;
    }
}

泛型集合与工具类

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

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

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

  • 好处:

    • 提高代码的重要性。

    • 防止类型转换异常,提高代码的安全性。

泛型类

package gather;
/**
 * 泛型类
 * 语法:类名<T>
 *     T类型占位符,表示一种引用类型,如果编写多个使用逗号隔开*/
public class Demo05<T> {
    //使用泛型T
    //创建变量
    T t;
    //泛型作为方法的参数
    public void show(T t){
        System.out.println(t);
    }
    //使用泛型作为方法的返回值
    public T getT(){
        return t;
    }
}
package gather;

public class Test {
    public static void main(String[] args) {
        //使用泛型类创建对象
        //注意:1.泛型只能使用引用类型,2.不同泛型类对象不能相互赋值
        Demo05<String> demo05=new Demo05<String>();
        demo05.t="hello";
        demo05.show("大家好");
        String string=demo05.getT();//大家好
        Demo05<Integer> demo051=new Demo05<Integer>();
        demo051.t=100;
        demo051.show(200);
        Integer integer= demo051.getT();//200
    }
}

泛型接口

两种使用方式:一种是使用前确定类型;一种是使用是确定类型。

泛型方法

package gather;
/**
 * 泛型方法
 * 语法:<T>返回值类型
 * */
public class Demo06 {
    //泛型方法
    public <T> T show(T t){
        System.out.println("泛型方法"+t);
        return t;
    }

}
package gather;

public class Test {
    public static void main(String[] args) {
        //调用泛型方法
        Demo06 demo06=new Demo06();
        demo06.show("zhangsan");
        demo06.show(200);
        demo06.show(3.14);//类型由传入的数据方法来定
    }
}

泛型集合

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

  • 特点:

    • 编译时即可检查,而非运行时抛出。

    • 访问时,不必类型转换(拆箱)。

    • 不同类型之间引用不能互相赋值,泛型不存在多态。

      package gather;
      
      import oop.demo01.demo05.A;
      
      import java.util.ArrayList;
      import java.util.Iterator;
      
      public class Demo07 {
          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);//xxx yyy
              }
              ArrayList<Student> arrayList1=new ArrayList<>();
              Student s1=new Student("刘德华",20);
              arrayList1.add(s1);
              Iterator<Student> it= arrayList1.iterator();
              while(it.hasNext())
              {
                  Student s=it.next();
                  System.out.println(s.toString());//Student[name=刘德华,age=20]
              }
          }
      }
      

Colletions工具类

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

  • 方法:

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

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

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

package gather;

import java.util.*;

/**Collections工具类使用
 * */

public class Demo17 {
    public static void main(String[] args) {
        List<Integer> list=new ArrayList<>();
        list.add(20);
        list.add(30);
        list.add(5);
        list.add(30);
        //sort排序
        System.out.println("排序之前:"+list.toString());//排序之前:[20, 30, 5, 30]
        Collections.sort(list);
        System.out.println("排序之后:"+list.toString());//排序之后:[5, 20, 30, 30]
        //binarySearch 二分查找
        int i=Collections.binarySearch(list,13);//
        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());//[5, 20, 30, 30]
        //reverse反转
        Collections.reverse(list);
        System.out.println("反转之后:"+list);//反转之后:[30, 30, 20, 5]
        //shuffle 打乱
        Collections.shuffle(list);
        System.out.println("打乱之后:"+list);//打乱之后:[5, 30, 20, 30]
        //补充:list转成数组
        Integer[] arr=list.toArray(new Integer[0]);
        System.out.println(Arrays.toString(arr));//[30, 30, 5, 20]
        //补充:数组转成集合
        String[] names={"张三","李四","王五"};
        List<String> list2=Arrays.asList(names);
        //集合是一个受限集合,不能添加和删除
        System.out.println(list2);//[张三, 李四, 王五]
        //基本类型数组转换成集合时,需要修改为包装类
        int[] nums={100,200,300,400};
        List<int[]> list3=Arrays.asList(nums);
        System.out.println(list3);
    }
}
posted @ 2023-05-25 20:35  努力的小L  阅读(24)  评论(0)    收藏  举报