集合

集合

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

  2. 集合内存的是对象的地址

  3. 和数组的区别:

    1. 数组长度固定,集合长度不固定

    2. 数组可以储存基本类型和引用类型,数组只能存储引用类型

    3. 位置:java.until.*;

collection体系集合

QQ图片20201006163516

Collection父接口

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

方法

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

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

  3. void clear()//清空此集合中的所有对象

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

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

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

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

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

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

 

 

迭代器:一个接口有hasnext(),next(),remove()函数,用hasnext遍历所有元素并取出

package com.yyl.www.chapter01;
/**
* Collection接口的使用
* 1.添加元素
* 2.删除元素
* 3.遍历元素
* 4.判断
* @author yyl*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo01 {
   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.toString());
       //删除元素
       //collection.remove("榴莲");
       //collection.clear();//清空集合
       //System.out.println("删除之后"+ collection.size());

       //遍历集合[重点]

         //使用增强for
       for (Object object:collection) {
           System.out.println(object);
      }
         //使用迭代器 (迭代器专门用来遍历集合的一种方式)
         //hasNext();有没有下一个元素
         //next();获取下一个元素
         //remove();删除当前元素
       Iterator it=collection.iterator();
       while(it.hasNext()){
           Object s=it.next();
           System.out.println(s);
           //collection.remove(s);//ConcurrentModificationException发生异常,迭代器使用过程中只能用迭代器方法
           //ConcurrentModificationException 并发异常,不允许并发修改
           it.remove();
      }
       System.out.println("元素个数"+collection.size());

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

 

  1. 集合添加对象实际上把对象的地址放入集合的空间中

 

package com.yyl.www.chapter01;

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

//collection使用,储存学生信息
public class Demo02 {
   public static void main(String[] args) {
       //新建collection对象
       Collection collection=new ArrayList();
       //1.添加数据
       Student s1=new Student("张三",20);
       Student s2=new Student("李四",18);
       Student s3=new Student("王五",22);
       collection.add(s1);
       collection.add(s2);
       collection.add(s3);
       collection.add(s3);
       System.out.println("元素个数"+collection.size());
       System.out.println(collection.toString());
       //删除
       collection.remove(s3);
       //collection.remove(new Student("王五",22));//无效语句
       System.out.println("删除之后"+collection.toString());
       //collection.clear();//清楚对象
       System.out.println("—————————————增强for—————————————");
       for (Object object:collection) {
           Student s=(Student)object;
           System.out.println(s.toString());
      }
       System.out.println("———————————————迭代器—————————————");
       Iterator iterator=collection.iterator();
       while(iterator.hasNext()){
           Student s=(Student)iterator.next();
           System.out.println(s.toString());
      }
       //判断
       System.out.println(collection.contains(new Student("王五",22)));//输出false,s3和这个新对象无关系
       System.out.println(collection.isEmpty());
  }
}

List接口

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

  2. 方法

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

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

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

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

package com.yyl.www.chapter01;

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

/*
* List子接口的使用
* 1.有下标,有顺序
* 2.可以重复*/
public class Demo03 {
   public static void main(String[] args) {
       //创建对象
       List list=new ArrayList<>();
       //添加元素
       list.add("苹果");
       list.add("小米");
       list.add(0,"华为");
       System.out.println("元素个数"+list.size());
       System.out.println(list.toString());
       //2.删除元素
       /*list.remove("苹果");
       list.remove(0);//删除脚标为0的元素
       System.out.println(list.toString());
        */
       //3.遍历
       //3.1使用for遍历
       System.out.println("—————————for循环———————————");
       for(int i=0;i<list.size();i++){
           System.out.println(list.get(i));
      }
       //3.2使用增强for
       System.out.println("——————————增强for———————————");
       for (Object object:list) {
           System.out.println(object);
      }
       //3.3使用迭代器
       System.out.println("———————————迭代器———————————");
       Iterator it= list.iterator();
       while(it.hasNext()){
           System.out.println(it.next());
      }
       //3.4使用列表迭代器
       //和Iterator的区别:1.ListIterator可以向前或者向后遍历,可以添加,删除,修改元素
       ListIterator lit=list.listIterator();
       System.out.println("————————使用列表迭代器——————————");
       while(lit.hasNext()){//正向
           System.out.println(lit.nextIndex()+":"+lit.next());
      }
       while(lit.hasPrevious()){//逆向,先让指针指向最后一个元素
           System.out.println(lit.previousIndex()+":"+lit.previous());
      }
       //4.判断
       System.out.println(list.contains("华为"));
       System.out.println(list.isEmpty());
       //5.获取
       System.out.println(list.indexOf("华为"));
  }
package com.yyl.www.chapter01;

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

public class Demo04 {
   public static void main(String[] args) {
       List list=new ArrayList();
       list.add(10);//list不能储存基本类型,此处包含自动装箱操作
       list.add(20);
       list.add(30);
       list.add(40);
       list.add(50);
       System.out.println("元素个数"+list.size());
       System.out.println(list.toString());
       //2.s删除操作
       //错误示范:list.remove(20);
       list.remove(new Integer(20));
       //list.remove((Object)20);
       //list.remove(0);
       System.out.println("删除元素"+list.size());
       System.out.println(list.toString());
       //3.补充方法subList();
       List sublist=list.subList(1,3);//左闭右开
       System.out.println(sublist.toString());
  }
}

List实现类

ArrayList【重点】

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

  2. jdk1.2版本,运行效率快,线程不安全

Vector

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

  2. jdk1.0版本,运行效率慢,线程安全

LinkedList

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

ArrayList使用

package com.yyl.www.chapter01;
/*
* ArrayList使用:
* 1. 储存结构:数组,查询遍历快,增删慢
* */
import java.util.*;

public class Demo05 {
   public static void main(String[] args) {
       //创建集合
       ArrayList arrayList=new ArrayList();
       //添加元素
       Student s1=new Student("刘德华",20);
       Student s2=new Student("郭富城",22);
       Student s3=new Student("梁朝伟",18);
       arrayList.add(s1);
       arrayList.add(s2);
       arrayList.add(s3);
       System.out.println("元素个数"+arrayList.size());
       System.out.println(arrayList.toString());
       //删除元素
       //arrayList.remove(new Student("刘德华",20));
       //System.out.println("删除之后"+arrayList.toString());
       //怎么用脚标删除

       //遍历元素(重点)
       //3.1使用迭代器
       Iterator it=arrayList.iterator();
       while(it.hasNext()){
           System.out.println((Student)it.next());
      }
       //3.2列表迭代器
       ListIterator lit=arrayList.listIterator();
       System.out.println("——————————使用列表迭代器————————");
       while(lit.hasNext()){
           Student s=(Student)lit.next();
           System.out.println(s.toString());
      }
       System.out.println("————————————逆序————————————");
       while(lit.hasPrevious()){
           System.out.println((Student)lit.previous());
      }
       //判断
       System.out.println(arrayList.contains(new Student("刘德华",20)));
       System.out.println(arrayList.isEmpty());
  }
}

关于contains和remove:使用object的equals方法,可以通过重写equals方法来判断是否包含或者删除

@Override//重写equals方法
public boolean equals(Object obj) {
   //判断两个对象是否诶同一个引用
   if(this==obj){
       return true;
  }
   //判断obj是否为null
   if(obj==null){
       return false;
  }
   //判断是否为同一个类型
   if(obj instanceof Student){
       //4.强制类型转换
       Student s=(Student)obj;
       //比较属性
       if(this.name.equals(s.getName())&&this.age==s.getAge()){
           return true;
      }
  }
   return false;
}

ArrayList源码解析

常量:

private static final int DEFAULT_CAPACITY = 10;//默认容量,没有添加任何元素时容量为0,添加任意元素后变成10,填满之后扩容,扩容到原来的1.5倍
transient Object[] elementData; // non-private to simplify nested class access存放元素的数组
private int size;//实际元素个数

add()方法:添加元素

    public boolean add(E e) {
       ensureCapacityInternal(size + 1);  // Increments modCount!!
       elementData[size++] = e;
       return true;
  }

   private void ensureCapacityInternal(int minCapacity) {
       ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
  }

   private void ensureExplicitCapacity(int minCapacity) {
       modCount++;

       // overflow-conscious code
       if (minCapacity - elementData.length > 0)
           grow(minCapacity);
  }

   private void grow(int minCapacity) {
       // overflow-conscious code
       int oldCapacity = elementData.length;
       int newCapacity = oldCapacity + (oldCapacity >> 1);
       if (newCapacity - minCapacity < 0)
           newCapacity = minCapacity;
       if (newCapacity - MAX_ARRAY_SIZE > 0)
           newCapacity = hugeCapacity(minCapacity);
       // minCapacity is usually close to size, so this is a win:
       elementData = Arrays.copyOf(elementData, newCapacity);
  }

Vector类(不常用)

package com.yyl.www.chapter02;

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

/*
* 演示:Vector集合使用
* 储存结构:数组
* */
public class Demo01 {
   public static void main(String[] args) {
       Vector vector=new Vector();
       //添加元素
       vector.add("草莓");
       vector.add("芒果");
       vector.add("西瓜");
       System.out.println("元素个数"+vector.size());
       //遍历
       //使用枚举器
       Enumeration en=vector.elements();
       while(en.hasMoreElements()){
           String s=(String)en.nextElement();
           System.out.println(s);
      }
       //判断
       System.out.println(vector.contains("西瓜"));
       System.out.println(vector.isEmpty());
       //补充
       //firstElement
       //lastElement
       //elementAt
       //
  }

LinkedList

package com.yyl.www.chapter02;

import com.yyl.www.chapter01.Student;

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

/*
* 实现LinkedList使用
* 1.储存结构:双向链表
* */
public class Demo02 {
   public static void main(String[] args) {
       //创建集合
       LinkedList linkedList=new LinkedList();
       //1.添加元素
       Student s1=new Student("刘德华",20);
       Student s2=new Student("郭富城",22);
       Student s3=new Student("梁朝伟",18);
       linkedList.add(s1);
       linkedList.add(s2);
       linkedList.add(s3);
       linkedList.add(s3);
       System.out.println("元素个数"+linkedList.size());
       System.out.println(linkedList.toString());

       //2.删除
       //linkedList.remove(0);
       //System.out.println("删除之后"+linkedList.size());

       //3.遍历
       //3.1for
       System.out.println("————————for—————————");
       for(int i=0;i< linkedList.size();i++){
           System.out.println(linkedList.get(i));
      }
       //3.2增强for
       System.out.println("———————增强for—————————");
       for (Object object:linkedList) {
           //Student s=(Student)object;
           //System.out.println(s.toString());
           System.out.println(object);
      }
       //3.3使用迭代器
       System.out.println("——————————迭代器———————————");
      /* Iterator it=linkedList.iterator();
       while(it.hasNext()){
           Student s=(Student)it.next();
           System.out.println(s.toString());
       }
       */
       ListIterator lit=linkedList.listIterator();
       while(lit.hasNext()){
           System.out.println(lit.next());
      }
       //4.判断
       //5.获取
       System.out.println(linkedList.indexOf(s1));
  }
}

泛型

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

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

  • 语法

    <T,...>T称为类型占位符,表示一种引用类型

  • 好处:1.提高代码的重用性

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

泛型类

package com.yyl.www.Generic;
/*
* 泛型类:
* 语法:类名<T>
* T是占位符,表示一种引用类型,如果编写多个,使用逗号隔开
*
*
* */
public class Demo01<T> {
   //使用泛型
   //创建变量
   T t;
   //不能创建泛型
   //T t=new T();
   //没使用泛型接口之前,不知道泛型类是什么类
       //作为方法的参数
   public void show(T t){
       System.out.println(t);
  }
   //泛型作为方法的返回值
   public T getT(){
       return t;
  }
}
package com.yyl.www.Generic;

public class test01 {
   public static void main(String[] args) {
       //使用泛型类创建对象
       //注意:泛型只能使用引用类型2.不同泛型类型不能相互复制
       Demo01<String> myGeneric=new Demo01<String>();
       myGeneric.t="hello";
       myGeneric.show("大家好");
       String string=myGeneric.getT();
       System.out.println(string);

       Demo01<Integer> myGeneric2=new Demo01<Integer>();
       myGeneric2.t=10;
       myGeneric2.show(200);
       Integer i=myGeneric2.getT();
       System.out.println(i);
  }
}

泛型接口

package com.yyl.www.Generic;
/*
* 泛型接口:
* 语法:接口名+<T>
*/
public interface Demo02<T> {
   String name="张三";
   //不能创建泛型
   //T t=new T();
   //没使用泛型接口之前,不知道泛型类是什么类
   T server(T t);
}
package com.yyl.www.Generic;
//泛型接口实现类,重写接口的方法
//实现泛型接口时提供泛型是什么类
public class Demo02Impl implements Demo02<String>{
   @Override
   public String server(String s) {//已知泛型类别,方法改变
       System.out.println(s);
       return s;
  }
}
package com.yyl.www.Generic;
//实现泛型类或者让接口实现类也变成泛型类
public class Demo02Impl02<T> implements Demo02<T>{
   @Override
   public T server(T t) {
       System.out.println(t);
       return t;
  }
}
package com.yyl.www.Generic;

public class test02 {
   public static void main(String[] args) {
       Demo02Impl impl=new Demo02Impl();
       impl.server("xxxxxxxx");
       Demo02Impl02 impl2=new Demo02Impl02();
       impl2.server("java");

  }
}

泛型方法

package com.yyl.www.Generic;
/*
* 泛型方法:
* 语法:<T> + 方法返回值类型*/
public class Demo03 {
   //泛型方法
   public <T> void show(T t){
       System.out.println("泛型方法"+t);
  }
}
package com.yyl.www.Generic;

public class test03 {
   public static void main(String[] args) {
       //调用泛型方法
       Demo03 s=new Demo03();
       s.show("hahha");
       s.show(20);
  }
}

泛型集合

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

  2. 特点:

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

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

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

set接口

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

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

set接口使用

HashSet【重点】

  • 基于HashCode实现元素不重复

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

TreeSer

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

hashset使用

package com.yyl.www.chapter03;

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

/*
* 测试set接口的使用
* 特点:1.无序,没有下标
* 2.不能重复*/
public class Demo01 {
   public static void main(String[] args) {
       Set<String> set=new HashSet<String>();
       //1.添加属性
       set.add("小米");
       set.add("华为");
       set.add("华为");//未添加成功
       set.add("苹果");
       System.out.println("元素个数"+set.size());
       System.out.println(set.toString());//无序
       //删除
       //set.remove("小米");
       //set.clear();
       //遍历
       //3.1增强for
       for (Object object:set) {
           System.out.println(object);
      }
       //迭代器
       Iterator it=set.iterator();
       while(it.hasNext()){
           System.out.println(it.next());
      }
       //4.判断
       System.out.println(set.contains("小米"));
       System.out.println(set.isEmpty());
  }
}
  • HashSet使用: 存储结构:哈希表:数组+链表+红黑树 存储过程:1.计算保存位置,如果位置为空,则直接保存,如果不为空,则执行第二步 2.再执行equals,如果equals方法为true,则认为是重复元素,否则则形成链表

package com.yyl.www.chapter03;

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;
  }
}
package com.yyl.www.chapter03;

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

/*
* HashSet使用:
* 存储结构:哈希表:数组+链表+红黑树
* 存储过程:1.计算保存位置,如果位置为空,则直接保存,如果不为空,则执行第二步
*       2.再执行equals,如果equals方法为true,则认为是重复元素,否则则形成链表
* */
public class Demo02 {
   public static void main(String[] args) {
       //创建集合
       HashSet<Person> persons=new HashSet<>();
       //添加数据
       Person s1=new Person("刘德华",20);
       Person s2=new Person("林志玲",22);
       Person s3=new Person("梁朝伟",25);
       persons.add(s1);
       persons.add(s2);
       persons.add(s3);
       persons.add(s3);//无法添加,重复,对象无法重复添加
       persons.add(new Person("梁朝伟",25));//成功添加
       //如何让new的元素判断相等,重写hashcode方法
       //重写hashcode方法后依然加入,只是添加方式为链表
       //重写equals方法让他无法添加
       System.out.println(persons.toString());
       //删除
       //persons.remove(s3);
       persons.remove(new Person("梁朝伟",25));//同样能删除
       System.out.println(persons.toString());
       //遍历
       //使用for循环
       for (Object object:persons) {
           System.out.println(object);
      }
       //使用迭代器
       Iterator<Person> it=persons.iterator();
       while(it.hasNext()){
           System.out.println(it.next());
      }
       //判断
       System.out.println(persons.contains(new Person("刘德华",20)));
       System.out.println(persons.isEmpty());
  }

#补充知识:重写hashcode方法时使用31

  1. 31时素数,减少散列冲突

  2. 31计算方便,i*31=(i<<5)-i

Treeset

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

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

  3. 元素对象类型必须实现Compareable接口,指定排序规则

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

  5. 使用

    package com.yyl.www.chapter03;

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

    /*
    * TreeSet的使用
    * 存储结构:红黑树*/
    public class Demo03 {
       public static void main(String[] args) {
           TreeSet<String> treeSet=new TreeSet<>();
           //添加元素
           treeSet.add("xyz");
           treeSet.add("abc");
           treeSet.add("hello");//存在排序
           //treeSet.add("xyz");重复,不在添加
           System.out.println("元素个数"+treeSet.size());
           System.out.println(treeSet.toString());
           //删除
       //   treeSet.remove("xyz");
       //   System.out.println(treeSet.toString());
           //遍历
           for (Object object:treeSet) {
               System.out.println(object);
          }
           Iterator<String> it=treeSet.iterator();
           while(it.hasNext()){
               System.out.println(it.next());
          }
           //判断
           System.out.println(treeSet.contains("xyz"));
           System.out.println(treeSet.isEmpty());
      }
    }
  6. 存储方式

package com.yyl.www.chapter03;

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

/*
* 使用treeSet保存数据
* 储存结构:红黑树
* 要求:元素必须实现Comparable接口,compareTo函数返回值为0则认为是重复元素
* */
public class Demo04 {
   public static void main(String[] args) {
       //创建集合
       TreeSet<Person> treeSet=new TreeSet<>();
       //添加元素
       Person s1=new Person("刘德华",20);
       Person s2=new Person("林志玲",22);
       Person s3=new Person("梁朝伟",25);
       treeSet.add(s1);
       treeSet.add(s2);
       treeSet.add(s3);
       System.out.println(treeSet.toString());/*ClassCastException 类型转换异常cannot be cast to java.
                                                 lang.Comparable
                                                 treeSet保存时会自动排序,没有给排序的规则,故无法进行排序
                                                 报出错误*/
       //2.删除
       treeSet.remove(new Person("梁朝伟",25));//能删除,通过compareTo函数判断
       System.out.println(treeSet.toString());
       //3.遍历
       //3.1foreach增强for
       for (Object object:treeSet) {
           System.out.println(object);
      }
       //3.2迭代器
       Iterator<Person> it =treeSet.iterator();
       while(it.hasNext()){
           System.out.println(it.next());
      }
       //4.判断
  }
}
  1. 补充

package com.yyl.www.chapter03;

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

/*
* TreeSet使用
* Comparator:实现定制比较(比较器)
* Comparable 可比较的*/
public class Demo06 {
   public static void main(String[] args) {
       TreeSet<Person> persons=new TreeSet<>(new Comparator<Person>() {//使用匿名内部类创建接口实现类
           @Override
           public int compare(Person o1, Person o2) {
               //先比较年纪再比较名字
               int n1=o1.getAge()-o2.getAge();
               int n2=o1.getName().compareTo(o2.getName());
               return n1==0?n2:n1;//认真分析
          }
      });
       Person s1=new Person("刘德华",20);
       Person s2=new Person("林志玲",22);
       Person s3=new Person("梁朝伟",25);
       Person s4=new Person("李四",25);
       persons.add(s1);
       persons.add(s2);
       persons.add(s3);
       persons.add(s4);
       System.out.println(persons.toString());
  }
}
  1. 案例

  2. package com.yyl.www.chapter03;

    import java.util.Comparator;
    import java.util.TreeSet;
    /*
    * 要求:使用TreeSet集合实现字符串按照长度进行排序
    * Comparator接口实现定制比较*/
    public class Demo07 {
       public static void main(String[] args) {
           TreeSet<String> treeSet=new TreeSet<>(new Comparator<String>() {
               @Override
               public int compare(String o1, String o2) {
                   int n1=o1.length()-o2.length();
                   int n2=o1.compareTo(o2);
                   return n1==0?n2:n1;
              }
          });
           //添加数据
           treeSet.add("helloworld");
           treeSet.add("pinguo");
           treeSet.add("xiangjiao");
           treeSet.add("beijin");
           treeSet.add("nanjin");
           treeSet.add("lisi");
           treeSet.add("cat");
           treeSet.add("huawei");
           System.out.println(treeSet.toString());
      }
    }

Map接口

 

1

 

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

  2. 方法

    V put(K key,V value);//将对象存入到集合中
    Object get(Object key);//根据键获取对应的值
    Set<K>;//返回所有key
    Collection<V> values();//返回包含所有值的Collection集合
    Set <Map.Entry<K,V>>//键值匹配的Set集合

Map接口的使用

package com.yyl.www.chapter04;

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

/*
* Map接口的使用
* 特点:1.储存键值对2.键不能重复3.无序*/
public class Demo01 {
   public static void main(String[] args) {
       //创建map集合
       Map<String,String> map=new HashMap<>();
       //添加元素
       map.put("cn","中国");
       map.put("uk","英国");
       map.put("usa","美国");
       map.put("cn","zhongguo");//后面添加的value覆盖前边的value
       System.out.println(map.toString());
      // map.remove("usa");
       //System.out.println("删除之后"+map.size());

       //3.遍历
       //3.1使用keySet,返回值为所有key的集合
       System.out.println("—————————keySet—————————");
       //Set<String> keyset=map.keySet();
       for(String key:map.keySet()){
           System.out.println(key+"="+map.get(key));
      }
       //3.2使用entrySet()方法,返回值为一对key和value的Map.entry组合
       //相比keySet遍历,效率高一点
       Set<Map.Entry<String,String>> entries= map.entrySet();/*此处的Entry<String,String>为Map的一
                                                               个内部接口
                                                              */
       for(Map.Entry<String,String> s:entries){
           System.out.println(s.getKey()+"="+s.getValue());
      }
       //4.判断
       System.out.println(map.containsKey("cn"));
       System.out.println(map.containsValue("泰国"));
  }
}

HashMap使用(重点)

构造函数

    • HashMap() 构造一个空的 HashMap ,默认初始容量(16)和默认负载系数(0.75)。

static final int TREEIFY_THRESHOLD = 8;//hashcode判断相等但equals判断不相等时在同一位置添加链表
                                         //当链表节点数大于8时,集合元素个数大于64时转化成红黑树
static final int MIN_TREEIFY_CAPACITY = 64;

static final int UNTREEIFY_THRESHOLD = 6;//当树节点小于6时转化成链表
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//hashmap初始容量大小
static final int MAXIMUM_CAPACITY = 1 << 30;//hashmap数组最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认加载因子,使用量大于0.75时进行扩容
transient Node<K,V>[] table;//哈希表中的数组
transient int size;//元素个数
package com.yyl.www.chapter04;

import com.yyl.www.chapter03.Person;

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

/*
* HashMap使用:
* 存储结构:哈希表(数组,链表,红黑树)
* 使用key的hashcode和equals作为重复的依据*/
public class Demo02 {
   public static void main(String[] args) {
       //创建对象
       HashMap<Student,String> students=new HashMap<>();
       //刚创建hashmap时没有添加元素,table=null,size=0,目的节省空间
       //添加元素
       Student s1=new Student("孙悟空",100);
       Student s2=new Student("猪八戒",101);
       Student s3=new Student("沙悟净",102);
       students.put(s1,"上海");
       students.put(s2,"北京");
       students.put(s3,"杭州");
       students.put(s3,"南京");
       students.put(new Student("沙悟净",102),"湖北");//重写hashcode和equals之后覆盖之前的value
       System.out.println("元素个数"+students.size());
       System.out.println(students.toString());
       //2.删除
       //students.remove(s1);
       System.out.println("删除之后"+students.toString());
       //3.遍历
       //使用keySet
       for(Student key:students.keySet()){
           System.out.println(key+"="+students.get(key));
      }
       //使用entrySet
      for(Map.Entry<Student,String> entry:students.entrySet()){
          System.out.println(entry.getKey()+"="+entry.getValue());
      }
      //4.判断
       System.out.println(students.containsKey(s1));
       System.out.println(students.containsKey(new Student("孙悟空",100)));
       System.out.println(students.isEmpty());
  }
}
package com.yyl.www.chapter04;

import java.util.Objects;

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

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

   public String getName() {
       return name;
  }

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

   public int getStuNo() {
       return stuNo;
  }

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

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

   @Override
   public boolean equals(Object o) {
       if (this == o) return true;
       if (!(o instanceof Student)) return false;
       Student student = (Student) o;
       return getStuNo() == student.getStuNo() &&
               getName().equals(student.getName());
  }

   @Override
   public int hashCode() {
       return Objects.hash(getName(), getStuNo());
  }
}

源码分析总结总结

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

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

  3. jdk1.8 当每个链表长度大于等于8,并且集合元素大于64时,会调整为红黑树,目的提高效率

  4. jdk1.8 当链表长度小于6,调整成链表

  5. jdk1.8以前,链表是头插法。jdk1.8之后是尾插法

Map结合其他实现类

  1. HashMap,jdk1.2版本,线程不安全,运行效率快:允许用null作为key或value

  2. HashTable,jdk1.0版本,线程安全,运行效率慢:不允许用null作为key和value

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

  4. TreeMap:实现了SortedMap接口(是map的子接口),可以对key自动排序

TreeMap使用

package com.yyl.www.chapter04;
/*
* TreeMap使用:
* 存储结构:红黑树*/
import java.util.Map;
import java.util.TreeMap;

public class Demo03 {
   public static void main(String[] args) {
       //新建集合
       TreeMap<Student,String> treeMap=new TreeMap<>();//其他方法,比较器
       //1.添加元素
       Student s1=new Student("孙悟空",100);
       Student s2=new Student("猪八戒",101);
       Student s3=new Student("沙悟净",102);
       treeMap.put(s1,"北京");
       treeMap.put(s2,"上海");
       treeMap.put(s3,"广州");
       treeMap.put(new Student("沙悟净",102),"南京");//学号相同认为元素相同,comparator比较规则
       System.out.println("元素个数"+treeMap.size());
       System.out.println(treeMap.toString());
       //2.删除元素
       treeMap.remove(new Student("沙悟净",102));
       System.out.println("删除之后"+treeMap.size());
       //3.1使用KeySet
       for(Student key: treeMap.keySet()){
           System.out.println(key+treeMap.get(key));
      }
       //3.2使用entrySet
       for(Map.Entry<Student,String> map: treeMap.entrySet()){
           System.out.println(map.getKey()+"="+map.getValue());
      }
       //4.判断
       System.out.println(treeMap.containsKey(new Student("沙悟净",102)));
       System.out.println(treeMap.isEmpty());
  }
}

Collection工具类

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

  2. 方法:

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

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

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

      package com.yyl.www.chapter04;

      import java.util.*;

      public class Demo04 {
         public static void main(String[] args) {
             List<Integer> list=new ArrayList<>();
             list.add(20);
             list.add(5);
             list.add(12);
             list.add(30);
             list.add(6);
             //1.sort
             System.out.println("排序前"+list.toString());
             Collections.sort(list);
             System.out.println("排序后"+list.toString());
             //2.binarySearch(二分查找),先排序,再查找
             int j=Collections.binarySearch(list,20);
             System.out.println(j);//返回key的对应位置
             //copy(复制)
             List<Integer> list2=new ArrayList<>();
             for(int i=0;i<list.size();i++){
                 list2.add(0);
            }
             Collections.copy(list2,list);//必须两个list集合大小一样才能复制
             System.out.println(list2);
             //reverse反转
             Collections.reverse(list);
             System.out.println("反转之后"+list);
             //shuffe 打乱
             Collections.shuffle(list2);
             System.out.println("打乱之后"+list2);
             //补充:把list转化成数组
             Integer[] l=list.toArray(new Integer[0]);//当new的数组长度小于list长度,返回list长度,若大于,则返回new的数组长度
             System.out.println(l.length);
             System.out.println(Arrays.toString(l));
             //数组转化成集合
             //集合是一个受限集合,不能添加和删除
             System.out.println("数组转化成集合");
             String[] names={"张三","李四","王五"};
             List<String> list3= Arrays.asList(names);
             //list3.add("zhaoliu");//转化过来的集合无法添加
             System.out.println(list3.toString());
             //int[] nums={100,200,300,400};
             //List<int[]> list4=Arrays.asList(nums);//集合里边每个数据变成数组,如何输出?
             //把基本类转化成集合类,需要修改为包装类型
             Integer[] nums={100,200,300,400};
             List<Integer> list4=Arrays.asList(nums);
             System.out.println(list4.toString());
        }
      }

       

posted @ 2020-10-13 20:36  Deair  阅读(137)  评论(0编辑  收藏  举报