集合框架知识汇总

news2024/10/7 14:34:05

集合框架

集合

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

  • 和数组的区别

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

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

  • 总结

    • List集合

      • 有序,有下标,元素可以重复(ArrayList,LinkedList,Vector)

    • Set集合

      • 无序,无下标,元素不可以重复(HashSet,TreeSet)

    • Map集合

      • 存储一对数据,无序,无下标,键不可重复,值可重复。(HashMap,HashTable,TreeMap)

    • Collections

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

Collection体系集合

Collection父接口

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

//Collection接口的使用

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

public class Demo1 {
    public static void main(String[] args) {
       //创建一个集合
        Collection collection=new ArrayList();
        //添加元素
        collection.add("花海");
        collection.add("枫");
        collection.add("晴天");
        System.out.println("元素个数:"+collection.size());
        System.out.println(collection);
        //删除元素
        collection.remove("晴天");
        System.out.println("元素个数:"+collection.size());
        System.out.println(collection);
        //遍历(掌握)
        //使用增强for
        for (Object object:collection) {
            System.out.println(object);
        }
        //迭代器(专门用来遍历集合)
        //hasNext();有没有下一个元素
        //next();获取下一个元素
        //remove();删除当前元素
        Iterator it= collection.iterator();
while (it.hasNext()){
    String object=(String)it.next();
    System.out.println(object);
    it.remove();
}
        System.out.println("元素个数"+collection.size());
//判断
        //判断元素是否存在
        System.out.println(collection.contains("花海"));
        System.out.println(collection.contains("晴天"));
        System.out.println(collection.isEmpty());
    }
}

 

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

    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 +
                '}';
    }
}
---------------------------------------
 import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

//Collection的使用(学生信息)
public class Demo2 {
    public static void main(String[] args) {
        //新建一个Collection对象
        Collection collection=new ArrayList();
        Student s1=new Student("林夕",18);
        Student s2=new Student("花海",22);
        Student s3=new Student("枫",12);
        //添加数据
        collection.add(s1);
        collection.add(s2);
        collection.add(s3);
        System.out.println("元素个数:"+collection.size());
        System.out.println(collection.toString());
        //删除
        collection.remove(s1);
        System.out.println("元素个数:"+collection.size());
        System.out.println(collection.toString());
        //遍历
        //增强for方法
        for (Object object:collection) {
            Student s=(Student)object;
            System.out.println(s.toString());
        }
        //迭代器
        Iterator it=collection.iterator();
        while (it.hasNext()){
          Student st=(Student) it.next();
            System.out.println(st.toString());
            //判断
            System.out.println(collection.contains(s1));
            System.out.println(collection.contains(s2));
            System.out.println(collection.isEmpty());
        }
    }
}   
   

 

 

List子接口

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

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

//List接口的使用
public class Demo1 {
    public static void main(String[] args) {
        //先创建集合
        List list=new ArrayList<>();
        //添加元素
        list.add("林夕");
        list.add("花海");
        list.add(0,"枫");
        list.add("晴天");
        list.add("七里香");
        System.out.println("元素个数"+list.size());
        System.out.println(list.toString());
        //删除元素
        list.remove("花海");
        list.remove(0);
        System.out.println("删除之后"+list.size());
        System.out.println(list.toString());
        //遍历
        //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());
        }
         //列表迭代器  ListIterator和Iterator的区别:可以向前或向后遍历,添加,删除,修改(.set())元素
        ListIterator lit =list.listIterator();
        //从前往后
         while (lit.hasNext()){
             System.out.println(lit.nextIndex()+":"+lit.next());
         }
         //从后往前
        while(lit.hasPrevious()){
            System.out.println(lit.previousIndex()+":"+ lit.previous());
        }
        //判断
        System.out.println(list.contains("林夕"));
        System.out.println(list.isEmpty());
        //获取元素位置
        System.out.println(list.indexOf("林夕"));
        }
}

 

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

public class Demo2 {
    public static void main(String[] args) {
        //创建list集合
        List list=new ArrayList<>();
        //添加数字数据(自动装箱,成为了包装类)
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
        System.out.println("元素个数:"+list.size());
        System.out.println(list.toString());
        //删除
        list.remove((Object) 20);//或者list.remove(0)
        System.out.println("元素个数:"+list.size());
        System.out.println(list.toString());
        // .sublist()返回子集合
        System.out.println(list.subList(1,3));
    }
}

List实现类

  • ArrayList

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

  • 源码分析

    • DEFAULT_CAPACITY=10;默认容量

    • elementDate存放元素的数组

    • size 实际元素个数

    • 如果没有向集合中添加任何元素,容量为零,添加任意一个元素以后,容量变为10,10以后,每次扩容后为1.5倍(10.》15)

ArrayList使用


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

public class Demo3 {
    public static void main(String[] args) {
        //创建ArrayList集合
        ArrayList arrayList=new ArrayList<>();
        Student s1=new Student("林夕",20);
        Student s2=new Student("花海",21);
        Student s3=new Student("晴天",22);
        Student s4=new Student("枫",23);
        //添加对象
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        arrayList.add(s4);
        System.out.println("元素个数:"+arrayList.size());
        System.out.println(arrayList.toString());
        //删除对象
       arrayList.remove((new Student("林夕",20)));
        System.out.println("删除之后:"+arrayList.size());// arrayList.remove(0);
        System.out.println(arrayList.toString());
        //遍历
        //迭代器
       Iterator it= arrayList.iterator();
       while(it.hasNext()){
          Student s=(Student) it.next();
           System.out.println(s.toString());
       }
        System.out.println("-------------------------");
       //列表迭代器
        ListIterator lit = arrayList.listIterator();
       while(lit.hasNext()){
           Student st=(Student) lit.next();
           System.out.println(st.toString());
       }
        System.out.println("-------------------------");
       while ((lit.hasPrevious())){
           Student std=(Student) lit.previous();
           System.out.println(std.toString());
       }
        System.out.println("-------------------------");
       //判断
        System.out.println(arrayList.contains(s2));
        System.out.println(arrayList.isEmpty());
        //查找
        System.out.println(arrayList.indexOf(s2));
 
 }
}
--------------------------------------------
    package 基础语法.Collection.Demo2;

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

    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 boolean equals(Object obj) {
        //判断是不是同一个对象
        if (this==obj){
            return true;
        }
        //判断是否为空
        if (obj==null){
            return false;
        }
        //判断是否为Student类型
        if (obj instanceof Student){
            Student s=(Student)obj;
            //比较属性
            if (this.name.equals(s.getName())&&this.age==s.getAge()){
                return true;
            }
        }
        //不满足条件false
        return false;
    }

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

    }
}

 

 

Vector

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

  • JDK1.0

import java.sql.SQLOutput;
import java.util.Enumeration;
import java.util.Vector;

public class Demo4 {
    public static void main(String[] args) {
        //创建Vector集合
        Vector vector=new Vector<>();
        Student s1=new Student("林夕",23);
        Student s2=new Student("花海",22);
        Student s3=new Student("枫",24);
        Student s4=new Student("晴天",25);
        //添加对象
        vector.add(s1);
        vector.add(s2);
        vector.add(s3);
        vector.add(s4);
        System.out.println("元素个数:"+vector.size());
        System.out.println(vector.toString());
         //删除
        System.out.println(vector.remove(0));
        //遍历
       Enumeration en= vector.elements();
       while (en.hasMoreElements()){
              Student s=(Student)en.nextElement();
           System.out.println(s);
       }
        //判断
        System.out.println(vector.contains(s2));
        //补充
        System.out.println(vector.firstElement());
        System.out.println(vector.lastElement());
        System.out.println(vector.elementAt(2));
    }
}

 

LinkedList

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

  • 源码分析

    • int size;集合的大小

    • Node first;链表的头节点

    • Node last ;链表的尾节点

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

//LinkedList
//存储结构,双向链表
public class Demo5 {
    public static void main(String[] args) {
        //创建LinkedList集合
        LinkedList linkedList=new LinkedList<>();
        Student S1=new Student("林夕",20);
        Student S2=new Student("花海",20);
        Student S3=new Student("枫",20);
        Student S4=new Student("晴天",20);
        //添加对象
        linkedList.add(S1);
        linkedList.add(S2);
        linkedList.add(S3);
        linkedList.add(S4);
        System.out.println(linkedList.size());
        System.out.println(linkedList.toString());
        System.out.println("-------------------------------");
        //遍历
        //for循环
        for (int i = 0; i < linkedList.size(); i++) {
            System.out.println(linkedList.get(i));
        }
        System.out.println("-------------------------------");
        //增强for循环
        for (Object object:linkedList) {
            Student s=(Student) object;
            System.out.println(s);
        }
        System.out.println("------------------------");
        //迭代器
        Iterator it=linkedList.iterator();
        while(it.hasNext()){
            Student s=(Student) it.next();
            System.out.println(s);
        }
        System.out.println("------------------------");
        //列表迭代器
            ListIterator lit= linkedList.listIterator();
        while(lit.hasNext()){
           Student s=  (Student)lit.next();
            System.out.println(s);
        }
        System.out.println("------------------------");
        //判断
        System.out.println(linkedList.contains(S2));
        //获取
        System.out.println(linkedList.indexOf(S2));
    }
}

 

ArrayList和Linkedlist的区别

  • ArrayList创建的地址连续 ,查询快,增删慢

  • LinkedList创建的不连续,查询慢,增删快

泛型

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

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

    • 语法<T····>T 称作类型占位符,表示一种引用类型

  • 好处

    • 提高代码的重用性

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

泛型类

//泛型类   语法  类名<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;
   }
}
===============================
    public class Test {
    public static void main(String[] args) {
        //使用泛型类创建对象
        //注意:1 泛型只能使用引用类型 2 不同泛型类型之间不能相互赋值

        MyGeneric<String> myGeneric=new MyGeneric<>();
        myGeneric.show("林夕");
        myGeneric.t="花海";
        String str=myGeneric.getT();

        MyGeneric<Integer>  myGeneric1=new MyGeneric<>();
        myGeneric1.show(200);
        myGeneric1.t=100;
        Integer integer=myGeneric1.getT();
    }
}

泛型接口

public interface MyGenericFace<T> {
    String name="林夕";
    T server(T t);
}
----------------------------------------
public class MyGenericFaceImp implements MyGenericFace<String>{
    @Override
    public String server(String s) {
        System.out.println(s);
        return s;
    }
}
---------------------------------------
    public class MyGenericFaceImp1<T> implements MyGenericFace<T>{
    @Override
    public T server(T t) {
        System.out.println(t);
        return t;
    }
}
-------------------------------------
     MyGenericFaceImp imp=new MyGenericFaceImp();
        imp.server("林夕");


        MyGenericFaceImp1<Integer> imp1=new MyGenericFaceImp1<>();
        imp1.server(123);

 

泛型方法

//泛型方法    语法  < T>返回值类型
public class MyGenericMethod {
   public <T>  T  show(T t){
       System.out.println("泛型方法:"+t);
       return t;
   }  
}
-------------------------
     //泛型方法
        MyGenericMethod myGenericMethod=new MyGenericMethod();
        myGenericMethod.show("林夕");
        myGenericMethod.show(123);

 

泛型集合

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

  • 特点

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

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

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

Set子接口

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

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

    set接口使用

  • import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    //测试Set接口的使用
    public class Demo1 {
        public static void main(String[] args) {
        //创建集合
        Set<String> set=new HashSet<>();
        //添加数据
        set.add("林夕");
        set.add("花海");
        set.add("枫");
        set.add("晴天");
        System.out.println(set.size());
        System.out.println(set.toString());
          //删除数据
            set.remove("林夕");
            System.out.println(set.toString());
            //遍历
            //增强for
            for (String string:set) {
                System.out.println(string);
            }
            System.out.println("--------------------------------");
            //使用迭代器
            Iterator<String> it=set.iterator();
            while (it.hasNext()){
                System.out.println( it.next());
            }
            System.out.println("----------------------------------");
            //判断
            System.out.println(set.contains("花海"));
            System.out.println(set.isEmpty());
    }
    }

    HashSet使用

  • 基于HashSet计算元素存放位置

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

  •  

    import java.util.HashSet;
    import java.util.Iterator;
    
    //HashSet集合的使用
    //存储结构  哈希表(数组+链表+红黑树)
    public class Demo2 {
        public static void main(String[] args) {
            //创建HashSet集合
            HashSet<String>  hashSet=new HashSet<>();
            //添加元素
            hashSet.add("林夕");
            hashSet.add("花海");
            hashSet.add("枫");
            hashSet.add("七里香");
            hashSet.add("晴天");
            System.out.println("元素个数:"+hashSet.size());
            System.out.println(hashSet.toString());
            //删除元素
            hashSet.remove("林夕");
            System.out.println("删除之后:"+hashSet.size());
            //遍历
            //增强for循环
            for (String string:hashSet) {
                System.out.println(string);
            }
            System.out.println("========================");
            //迭代器
            Iterator<String> it=hashSet.iterator();
            while (it.hasNext()){
                System.out.println(it.next());
            }
            System.out.println("=============================");
            //判断
            System.out.println(hashSet.contains("七里香"));
            System.out.println(hashSet.isEmpty());
        }
    }
    

     

    public class 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 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;
        }
    }
    ============================================================
        import java.util.HashSet;
    import java.util.Iterator;
    
    //HashSet的使用
    //1 根据Hashcode计算保存的位置,如果此位置为空则直接保存,如果不为空执行第二步
    //2  在执行equals方法,如果equals方法为true,则认为重复,否则,形成链表
    public class Demo3 {
        public static void main(String[] args) {
            //创建persons集合
            HashSet<Person> persons=new HashSet<>();
            //添加元素
            Person p1=new Person("林夕",18);
            Person p2=new Person("花海",18);
            Person p3=new Person("晴天",18);
            Person p4=new Person("枫",18);
            persons.add(p1);
            persons.add(p2);
            persons.add(p3);
            persons.add(p4);
            persons.add((new Person("花海",18)));
            System.out.println(persons.size());
            System.out.println(persons.toString());
            //删除数据
            persons.remove(p1);
            System.out.println("删除之后:"+persons.size());
            System.out.println(persons.toString());
            //遍历
          //增强for
            for (Person person:persons) {
                System.out.println(person);
            }
            //迭代器
            Iterator<Person> it=persons.iterator();
            while(it.hasNext()){
                System.out.println(it.next());
            }
            //判断
            System.out.println(persons.contains(p2));
            System.out.println(persons.isEmpty());
        }
    }

     

  • 注意点(重写hashcode时为什么使用31?)

    • 31是质数,尽量减少散列冲突

    • 提高执行效率(31*i=(i>>5)-i)

    • TreeSet

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

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

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

  • 通过CompareTo方法确定是否为重复元素

     

  • 
    public 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 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;
        }
    }
    --------------------------------------
        
    import java.util.Iterator;
    import java.util.TreeSet;
    
    //TreeSet的使用
    //存储结构(红黑树)
    //元素必须实现Comparable接口,compareTo()方法返回值为0,认为为重复元素
    public class Demo5 {
        public static void main(String[] args) {
    
        TreeSet<Person> personTreeSet=new TreeSet<>();
        Person p1=new Person("xyz",19);
        Person p2=new Person("asd",17);
        Person p3=new Person("qwe",18);
        Person p4=new Person("asd",16);
            personTreeSet.add(p1);
            personTreeSet.add(p2);
            personTreeSet.add(p3);
            personTreeSet.add(p4);
            System.out.println(personTreeSet.size());
            System.out.println(personTreeSet.toString());
            personTreeSet.remove(p1);
            System.out.println(personTreeSet.size());
            for (Person person:personTreeSet
                 ) {
                System.out.println(person);
            }
           Iterator<Person > it= personTreeSet.iterator();
            while (it.hasNext()){
                System.out.println(it.next());
            }
            System.out.println(personTreeSet.contains(p2));
            System.out.println(personTreeSet.isEmpty());
    }
    }

 

 

  • Comparator**:实现定制比较(比较器)

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

//TreeSet接口
//Comparator:实现定制比较(比较器)
public class Demo6 {
    public static void main(String[] args) {
        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 p1=new Person("xyz",19);
        Person p2=new Person("asd",17);
        Person p3=new Person("qwe",16);
        Person p4=new Person("asd",16);
        personTreeSet.add(p1);
        personTreeSet.add(p2);
        personTreeSet.add(p3);
        personTreeSet.add(p4);
        System.out.println(personTreeSet.size());
        System.out.println(personTreeSet.toString());
    }
}

TreeSet案例

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

*//TreeSet**使用

**//comparator**实现字符串排序
*public class Demo7 {
    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("asd");
    treeSet.add("asdf");
    treeSet.add("asdgh");
    treeSet.add("asdjjll");
    treeSet.add("asdtdwggtghrtr");
    System.*out*.println(treeSet.toString());
}
}

 

 Map体系集合

 

  • Map接口特点

    • 用于储存任意键值对(key-value)

    • 键:无序,无下标,不允许重复(唯一)

    • 值:无序,无下标,允许重复

Map父接口

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

//Map接口的使用    1储存的是键值对,2键不可以重复,值可以重复,3无序
public class Demo1 {
    public static void main(String[] args) {
        //创建Map集合
        Map<String,String>  map=new HashMap<>();
        //添加元素
        map.put("林","夕");
        map.put("花","海");
        map.put("晴","天");
        map.put("一路","向北");
        System.out.println("元素个数:"+map.size());
        System.out.println(map.toString());
        //删除元素
        map.remove("林");
        System.out.println("删除之后:"+map.size());
        //遍历
        //1 使用KeySet();
        for (String key: map.keySet()
             ) {
            System.out.println(key+"----"+map.get(key));
        }
        System.out.println("---------------");
        //2 使用entrySet();方法
        for (Map.Entry<String,String> entry: map.entrySet()
             ) {
            System.out.println(entry.getKey()+"---------------"+entry.getValue());
        }
        System.out.println("---------------------------------------");
        //判断
        System.out.println(map.containsKey("花"));
        System.out.println(map.containsValue("向北"));
        System.out.println(map.isEmpty());
    }
}

 

Map集合的实现类

  • HashMap

    • 线程不安全,运行效率快:允许null作为key或者value

import java.util.Objects;

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

    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 "name:"+name+"age:"+age;
    }

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

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
=========================================
    //HashMap集合的使用
//存储结构:哈希表(数组+链表+红黑树)
import java.util.HashMap;
import java.util.Map;

public class Demo2 {
    public static void main(String[] args) {
        //创建HashMap集合
        HashMap<Student,String> hashMap=new HashMap<>();
        //添加元素
        Student s1=new Student("林夕",18);
        Student s2=new Student("花海",16);
        Student s3=new Student("枫",17);
        Student s4=new Student("晴天",19);
        hashMap.put(s1,"西安");
        hashMap.put(s2,"广州");
        hashMap.put(s3,"上海");
        hashMap.put(s4,"北京");
        hashMap.put(new Student("晴天",19),"北京");
        System.out.println("元素个数:"+hashMap.size());
        System.out.println(hashMap.toString());
        //删除
        hashMap.remove("s1");
        System.out.println("删除之后:"+hashMap.size());
        //遍历
        //keySet();方法
        for (Student key: hashMap.keySet()
             ) {
            System.out.println(key+"----------"+hashMap.get(key));
        }
        System.out.println("=========================");
        //entrySet();方法
        for (Map.Entry<Student,String> entry: hashMap.entrySet()
             ) {
            System.out.println(entry.getKey()+"------"+entry.getValue());
        }
        System.out.println("==========================");
        //判断
        System.out.println(hashMap.containsKey("s2"));
        System.out.println(hashMap.containsValue("上海"));
        System.out.println(hashMap.isEmpty());
    }
}

 

  • 源码分析

1 static final int  DEFAULT_INITIAL_CAPACITY=1<<4;//hashMap初始容量(16)
2 static final int  MAXIMUM_CAPACITY=1<<30;//hashmap的数组最大容量
3 static final float DEFAULT_LOAD_FACTOR=0.75f;//默认加载因子
4 static final int  TREEITY_THRESHOLD=8;//JDK1.8 当链表长度大于8时,调整成红黑树
5 static final int  UNTREEIFY_THRESHOLD=6;//JDK1.当链表长度小于6时,调整成链表
6 static final int  MIN_TREEIFY_CAPAITY=64;//JDK1.8;当链表长度大于8时,并且集合元素个数大于等于64时,调整成红黑树
7 transient Node<K,V>[] table;//哈希表中的数值
8 size;//元素个数
  • 总结

    • HashMap刚创建时,table时null,为了节省空间,当添加第一个元素时,table容量调整为16;

    • 当元素个数大于阈值(16*0.75=12)时,扩容后的大小变为原来的两倍。目的是减少调整元素的个数

    • JDK1.8以前,链表是头插入,JDK1.8以后是尾插入

  • Hashtable:

    • 线程安全,运行效率慢,不允许null作为key或是value

  • Properties:

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

  • TreeMap:

    • 实现了SortedMap接口,可以对key进行自动排序

import java.util.Objects;

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

    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 "name:"+name+"age:"+age;
    }

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

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

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

------------------------------
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

//TreeMap的使用
public class Demo3 {
    public static void main(String[] args) {
        //创建集合
        TreeMap<Student,String> treeMap=new TreeMap<>();
        //添加对象
        Student s1=new Student("林夕",18);
        Student s2=new Student("花海",16);
        Student s3=new Student("枫",17);
        Student s4=new Student("晴天",19);
        treeMap.put(s1,"西安");
        treeMap.put(s2,"广州");
        treeMap.put(s3,"上海");
        treeMap.put(s4,"北京");
        System.out.println(treeMap.size());
        System.out.println(treeMap.toString());
        //删除
        treeMap.remove(s1);
        System.out.println(treeMap.size());
        //遍历
        //使用keySet
        for (Student key:treeMap.keySet()
             ) {
            System.out.println(key+"------"+treeMap.get(key));
        }
        System.out.println("========================");
        
        for (Map.Entry<Student,String>  entry:treeMap.entrySet()
             ) {
            System.out.println(entry.getKey()+"----------"+entry.getValue());
        }
        System.out.println("==============================");
        //判断
        System.out.println(treeMap.containsKey(s1));
        System.out.println(treeMap.containsValue("上海"));
        System.out.println(treeMap.isEmpty());
    }
}

 

 

 

Collections工具类

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

import java.util.*;

//Collections工具类的使用
public class Demo2 {
    public static void main(String[] args) {
        //创建集合
        List<Integer>  list=new ArrayList<>();
        //添加元素
        list.add(12);
        list.add(2);
        list.add(124);
        list.add(5);
        list.add(16);
        list.add(18);
        list.add(10);
        //sort();排序
        System.out.println("排序之前:"+list.toString());
        Collections.sort(list);
        System.out.println("排序之后:"+list.toString());
        //binarySeach二分查找
      int num=  Collections.binarySearch(list,10);
        System.out.println(num);
        //copy复制
        List<Integer> dest=new ArrayList<>();
        for (int j = 0; j <list.size() ; j++) {
            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={12,3345,6677,};
        List<Integer> list3=Arrays.asList(nums);
        System.out.println(list3);
    }
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/621991.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

软考网工易混淆知识点总结(持续更新中,按照知识点先后排序)

1.数据编码--原码、反码和补码 原码 数值前面增加了一位符号位(即最高位为符号位)&#xff0c;该位为0时表示正数&#xff0c;为1时则表示负数&#xff0c;其余各位表示数值的大小反码 正数的反码与原码相同&#xff0c;负数的反码符号位为1&#xff0c;其余各位为该数绝对值的…

大型语言模(LLM) : 提示词工程(一)

今天我学习了DeepLearning.AI的 Prompt Engineering 的在线课程&#xff0c;我想和大家一起分享一下该门课程的一些主要内容。 下面是我们访问大型语言模(LLM)的主要代码&#xff1a; import openaiopenai.api_key XXXXXXXXXdef get_completion(prompt, model"gpt-3.5-…

高性能分布式API网关Kong

目录 1 kong网关简介2 为什么需要 API 网关2.1 和Spring Cloud Gateway区别 3 为什么要使用kong3.1 kong的组成部分3.2 Kong网关的特性 4 kong网关架构4.1 Kong网关请求流程 5 kong 部署5.1 搭建网络5.2 搭建数据库环境5.3 kong网关部署5.3.1 初始化kong数据5.3.2 启动Kong容器…

【项目】树莓派4B镜像安装

本文主要记录下如何使用Raspberry Pi image 软件进行树莓派镜像进行安装。 官网&#xff1a;Raspberry Pi OS – Raspberry Pi 百度网盘&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1G7z1Fdvk5Chmhj894WPU3A 提取码&#xff1a;xnzw 一、格式化SD卡 若SD卡存在…

释放潜能——解读新时代OEM竞争规则,打造精雕细琢的用户体验

从消费零售全领域的实践观察来看&#xff0c;仅仅凭借产品赢得竞争的时代已经过去&#xff0c;商业模式创新体现在越来越多企业向“产品服务”转变&#xff0c;向用户全生命周期需求挖掘转变。企业与消费者之间的关系从过去的一次性、断点式产品交易&#xff0c;转向持续性、覆…

读写ini配置文件(C++)

文章目录 1、为什么要使用ini或者其它(例如xml,json)配置文件&#xff1f;2、ini文件基本介绍3、ini配置文件的格式4、C读写ini配置文件5、 代码示例6、 配置文件的解析库 文章转载于&#xff1a;https://blog.csdn.net/weixin_44517656/article/details/109014236 1、为什么要…

基于 Web 和 Deep Zoom 的高分辨率大图查看器的实践

基于 Web 和 Deep Zoom 的高分辨率大图查看器的实践 高分辨率大图像在 Web 中查看可以使用 Deep Zoom 技术&#xff0c;这是一种用于查看和浏览大型高分辨率图像的技术&#xff0c;它可以让用户以交互方式浏览高分辨率大图像&#xff0c;并且能够在不影响图像质量的情况下进行…

搭建个人网站 保姆级教程(四)Navicat链接mySql 失败

长时间没有折腾云服务器上的mysql了&#xff0c;今天再次使用Navicat连接云服务器上的mysql时&#xff0c;输入密码报错&#xff01; 1130 - Host ‘119.130.212.168’ is not allowed to connect to this MySQL server 1.于是Royal TSX 远程服务器查看mysql的状态 systemctl …

通达信标记文字中可能用到的特殊符号大全

特殊符号是难以直接输入的符号&#xff0c;特殊符号是符号的一种&#xff0c;比如说圆圈&#xff08;〇&#xff09;、叉号&#xff08;✕、✖、✘&#xff09;、五角星&#xff08;★、☆&#xff09;、勾号&#xff08;✓、✔&#xff09; 。 01.特殊符号简表 ♠♣♧♡♥❤…

chatgpt赋能python:Python强制取整:如何在Python中正确进行取整操作

Python强制取整&#xff1a;如何在Python中正确进行取整操作 Python是一种广泛使用的编程语言&#xff0c;有许多不同的用途&#xff0c;包括数据分析、web开发、机器学习、科学计算等等。Python语言非常容易学习和使用&#xff0c;但有时候它的行为可能会出人意料&#xff0c…

alpa概览

文章目录 背景alpa简介DeviceMesh跨 DeviceMeshes 的 GPU Buffer管理Ray CollectivePipeline parallelism runtime orchestration运行时 背景 LLM训练有3D并行的需求&#xff08;alpa将数据并行视为张量并行&#xff0c;即张量沿batch切分&#xff09; 算子间并行的通信成本小…

【Vue】父子组件传参 孙子调用爷爷的方法 provide inject

一. 父传子 父组件先在data中定义要传给子组件的属性名父组件在中引入子组件在components中注册使用步骤 3 中注册好的子组件在 3 中&#xff0c;父传子 &#xff08;1&#xff09;利用 : 将父组件的对象、数组、字符串等传给子组件&#xff0c;供子组件使用 &#xff08;2&am…

Rocky Linux9安装教程

序言 Centos废了&#xff0c;最近在考虑将服务器迁移至Rockylinux系统&#xff0c;在这里记录下安装过程 当前安装版本RockyLinux9.2&#xff08;minimal版本&#xff09;&#xff0c;VMware Fusion专业版13.0.2 创建虚拟机 第一步&#xff1a; 先下载好ISO文件&#xff0c…

python-高级特性

文章目录 1.生成式2.生成器3.闭包4.装饰器&#xff08;1&#xff09;万能装饰器的实现&#xff08;2&#xff09;含参数的装饰器&#xff08;3&#xff09;多装饰器 5.内置高阶函数 1.生成式 列表生成式就是一个用来生成列表的特定语法形式的表达式。是Python提供的一种生成列表…

2023.6.7小记——什么是FPGA?

最近打算开始继续做一些个人分享&#xff0c;已经太久时间没有写文章了&#xff0c;感觉这样下去肯定不是个好事&#xff0c;当程序员当然是要保持分享~ 标题就暂时先以每天我认为最重要的一点来取&#xff0c;内容不仅限于此。 1. 什么是FPGA&#xff1f; 全称是Field-Progra…

PCL 点云均值漂移算法(MeanShift)

文章目录 一、简介二、实现代码三、实现效果参考资料一、简介 均值漂移算法是一种非常经典的层次聚类方式,已在二维图像中得到了广泛的应用。这里我们也已二维图像为例来阐述其整个计算过程: 算法基本思想:如下图所示,左侧为实际的图像特征的分布,右侧为基于图像特征分布计…

Linux操作系统——第二章 进程控制

目录 进程创建 fork函数初识 fork函数返回值 写时拷贝 fork常规用法 fork调用失败的原因 进程终止 进程退出场景 进程常见退出方法 _exit函数 exit函数 return退出 进程等待 进程等待必要性 进程等待的方法 wait方法 waitpid方法 获取子进程status 进程程序…

接口测试框架实战 | 通用 API 封装实战

接口测试仅仅掌握 Requests 或者其他一些功能强大的库的用法&#xff0c;是远远不够的&#xff0c;还需要具备能根据公司的业务流程以及需求去定制化一个接口自动化测试框架的能力。所以&#xff0c;接下来&#xff0c;我们主要介绍下接口测试用例分析以及通用的流程封装是如何…

火龙果MM32F3273G8P开发板MindSDK开发教程3 - Sysclk的配置

Sysclk的配置 1、时钟初始化流程 一般流程为startup_mm32f3273g.s中调用system_mm32f3273g.c中的SystemInit函数完成系统时钟的初始&#xff0c;而system_mm32f3273g.c中函数是空的。 原来MindSdk时钟初始化的流程放到了clock_init.c中。 2、采用外部高速时钟源 先弄清几个…

Effective第三版 中英 | 第二章 创建和销毁对象 | 通过私有构造器强化不可实例化的能力

文章目录 Effective第三版前言第二章 创建和销毁对象通过私有构造器强化不可实例化的能力 Effective第三版 前言 大家好&#xff0c;这里是 Rocky 编程日记 &#xff0c;喜欢后端架构及中间件源码&#xff0c;目前正在阅读 effective-java 书籍。同时也把自己学习该书时的笔记…