黑马程序员------java基础----集合

 

 集合框架

为什么会出现这么多容器?

因为每一个容器对数据的存储方式都有不同,这个存储方式称之为:数据结构。

一、为什么出现集合类?

        面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式。

二、数组和集合类同是容器,有何不同?

        数组虽然也可以存储对象,但长度是固定的;集合长度是可变的。数组中可以存储基本数据类型,集合只能存储对象。

三、集合类的特点

        集合只用于存储对象,集合长度是可变的,集合可以存储不同类型的对象

  Collection

        Collection是集合框架中的常用接口。其下有两个子接口:List(列表),Set(集)。

       所属关系:

Collection

                     |--List//元素是有序的,元素可以重复。因为该集合体系有索引。

                     |--Set//元素是无序的,元素不可以重复。

一、Collection接口中的常见操作

1、添加元素

        add(Object  obj); //add方法的参数类型是Object。以便于接收任意类型对象。

2、删除元素

        remove(Object  obj);

        removeAll(另一集合);//调用者只保留另一集合中没有的元素。

        clear();//清空集合

3、判断元素

        contains(Object  obj);//判断是否存在obj这个元素

        isEmpty();//是否为空

4、获取个数,集合长度

        size();

5、取交集

        retainAll(另一集合);//调用者只保留两集合的共性元素。

注:集合中存储的都是对象的引用(地址)。

package atheima;

import java.util.ArrayList;
import java.util.Iterator;
/**
 * add方法的参数类型是object ,以便于接收任意类型对象。
 * 集合中存储的都是对象的引用或是地址
 * 
 *
 */
public class CollectionDemo 
{
    public static void main(String[] args) 
    {
        method_2();
        //method_1();
        method_get();
    }
    //取元素
    public static void method_get()
    {
        ArrayList a1=new ArrayList();
        //添加元素
        a1.add("hhh");
        a1.add("h");
        a1.add("hhhh");
        Iterator it=a1.iterator();
        while(it.hasNext())
        {
            sop(it.next());
        }        
     }
    public static void method_2()
    {
        ArrayList a1=new ArrayList();
        //添加元素
        a1.add("hhh");
        a1.add("h");
        a1.add("hhhh");
        ArrayList a2=new ArrayList();
        //添加元素
        a2.add("hhh");
        a2.add("hh");
        a2.add("hh");
        //a1.retainAll(a2);//取交集,a1中只会保留和a2中相同的元素
        a1.removeAll(a2);//删除和a2相同的元素
        sop("a1个数:"+a1);
        sop("a2个数:"+a2);
        
    }
        public static void method_1()
        {
            //创建一个集合容器,使用Collection接口的子类ArrayList
            ArrayList a1=new ArrayList();
            //添加元素
            a1.add("hhh");
            a1.add("hh");
            a1.add("hh");
            //打印集合
            sop(a1);
            //删除元素
            a1.remove("hhh");
            //a1.clear();//清空集合
            //判断元素
            sop("hh是否存在"+a1.contains("hh"));//--->true
            sop("集合是否为空?"+a1.isEmpty());//-->false
            //获取个数,集合长度
            sop("size--->"+a1.size());
            //打印改变后的集合
            sop(a1);
        }

    private static void sop(Object obj) {
        System.out.println(obj);
        
    }
    
}

二、迭代

1、什么是迭代器:其实就是集合的取出元素的方式。

        对于集合的元素取出这个动作:

        当不足以用一个函数来描述,需要用多个功能来体现,所以就将取出这个动作封装成一个对象来描述。就把取出方式定义在集合的内部,这样取出方式就可以直接访问集合内部的元素。那么取出方式就被定义成了内部类。

        而每一个容器的数据结构不同,所以取出的动作细节也不一样。但是都具有共性内容: 判断和取出。那么就可以将这些共性抽取。

        那么这些内部类都符合一个规则(或者说都抽取出来一个规则)。该规则就是Iterator。通过一个对外提供的方法:iterator();,来获取集合的取出对象。

         因为Collection中有iterator方法,所以每一个子类集合对象都具备迭代器。

2、迭代的常见操作

        hasNext();//有下一个元素,返回真

        next();//取出下一个元素

        remove();//移除

注:在迭代时循环中next调用一次,就要hasNext判断一次。

使用:

         ArrayList a=newArrayList();//创建一个集合

        Iteratorit=a.iterator();//获取一个迭代器,用于取出集合中的元素。

        第一种打印方式:

                for(Iterator iter = a.iterator();iter.hasNext();  )

                {

                           System.out.println(iter.next());

                }

       第二种打印方式:

                 Iteratoriter = a.iterator();

                while(iter.hasNext())

               {

                           System.out.println(iter.next());

               }

第三讲     List

一、List

组成

        List:元素是有序的,元素可以重复。因为该集合体系有索引。

            |--ArrayList:底层的数据结构使用的是数组结构。特点:查询速度很快。但是增删稍慢。线程不同步。

            |--LinkedList:底层使用的是链表数据结构。特点:增删速度很快,查询稍慢。

            |--Vector:底层是数组数据结构。线程同步。被ArrayList替代了。

二、List的特有方法

        凡是可以操作角标的方法都是该体系特有的方法。

1、增

        boolean  add(index,element);//指定位置添加元素

        Boolean  addAll(index,Collection);//在指定位置增加给定集合中的所有元素,若省略位置参数,则在当前集合的后面依次添加元素

2、删

        Boolean  remove(index);//删除指定位置的元素

3、改

        set(index,element);//修改指定位置的元素。

4、查

        get(index);//通过角标获取元素

        subList(from,to);//获取部分对象元素

5、其他

        list  Iterator();//List特有的迭代器

        indexOf(obj);//获取元素第一次出现的位置,如果没有则返回-1

注:List集合判断元素是否相同,移除等操作,依据的是元素的equals方法。

三、ListIterator

1、概述

        ListIterator是List集合特有的迭代器,是Iterator的子接口。

       在迭代时,不可以通过集合对象的方法操作集合中的元素。因为会发生ConcurrentModificationException并发修改异常。

如下:

public static void method_get()
 {
  ArrayList a1=new ArrayList();
  //添加元素
  a1.add("hhh");
  a1.add("h");
  a1.add("hhhh");
  Iterator it=a1.iterator();
  while(it.hasNext())
  {
   Object obj=it.next();
   if (obj.equals("h"))
    a1.add("jjj");--------->会发生异常,结果输出hhh,h。。。异常。
System.out.println(obj)
  }  
  }

所以在迭代器时,只能用迭代器的方法操作元素。可是Iterator方法是有限的,只能对元素进行判断,取出,删除的操作。如果想要其他的操作,如添加、修改等,就需要使用其子接口:List  Iterrator。该接口只能通过List集合的ListIterator方法获取。

2、ListIterator特有的方法

        add(obj);//增加

        set(obj);//修改为obj

        hasPrevious();//判断前面有没有元素

        previous();//取前一个元素

四、枚举Enumeration

枚举:

        就是Vector特有的取出方式。Vector有三种取出方式。

        其实枚举和迭代是一样的。因为枚举的名称以及方法的名称都过长。所以被迭代器取代了。

特有方法:

         addElement(obj);//添加元素,相当于add(obj);

         Enumerationelements();//Vector特有取出方式(枚举)

         hasMoreElements();//相当于Iterator的hasNext()方法

         nextElements();//相当于Iterator的next()方法

例: 

package atheima;

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

public class VerctorDemo { 
    public static void sop(Object obj){
        System.out.println(obj);
    }
 public static void main(String[] args)
    {  
     Vector v1=new Vector();
     v1.add("hh");
     v1.add("hahha");
     sop(v1);
     Enumeration e1=v1.elements();
     while (e1.hasMoreElements()) {
        sop(e1.nextElement());
    }

    } 
}

五、LinkedList

        LinkedList:底层使用的是链表数据结构。特点:增删速度很快,查询稍慢。

特有方法:

1、增

        addFirst();

        addLast();//往尾部放

2、获取

        //获取元素,但不删除元素。如果集合中没有元素,会出现NoSuchElementException

        getFirst();

        getLast();

3、删

        //获取元素,并删除元素。如果集合中没有元素,会出现NoSuchElementException

        removeFirst();移除并返回此列表的第一个元素。

        removeLast();移除并返回此列表的最后一个元素

JDK1.6以后,出现了替代方法。

1、增

        offerFirst();在此列表的开头插入指定的元素。

        offerLast();在此列表末尾插入指定的元素。

2、获取

        //获取元素,但是不删除。如果集合中没有元素,会返回null。

        peekFirst();获取但不移除此列表的第一个元素;如果此列表为空,则返回 null

        peekLast();获取但不移除此列表的最后一个元素;如果此列表为空,则返回 null

3、删

        //获取元素,并删除元素。如果集合中没有元素,会返回null。

        pollFirst();获取并移除此列表的第一个元素;如果此列表为空,则返回 null

        pollLast(); 获取并移除此列表的最后一个元素;如果此列表为空,则返回 null

package atheima;

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

public class LinkedListDemo { 
    public static void sop(Object obj){
        System.out.println(obj);
    }
 public static void main(String[] args)
    {  
     LinkedList link=new LinkedList();
     link.addFirst("hh0");
     link.addFirst("hh1");
     link.addFirst("hh2");
     link.addFirst("hh3");
//     sop(link);//------>输出结果hh3,hh2,hh1,hh0
//     sop(link.getFirst());//---->hh3
//     sop(link.getLast());//--->hh0
//     sop(link.removeFirst());//--->hh3
//     sop("size="+link.size());//--->3
     sop(link.offerFirst("hh4"));//--->true
     sop(link.peekFirst());//--->hh4
     sop(link.pollFirst());//-->hh4
     while(!link.isEmpty())
     {
         sop(link.removeFirst());//--->hh3,hh2,hh1,hh0
     }
    }
}
package atheima;
//使用Linkedlist模拟一个队列数据结构
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.Vector;

import org.hamcrest.core.IsNull;

class DuiLie
{
    private LinkedList link;
    public DuiLie() {
        link=new LinkedList();
    }
    public void myAdd(Object obj)
    {
        link.addFirst(obj);
    }
    public Object myGet()
    {
        return link.removeFirst();
    }
    public boolean isNull()
    {
        return link.isEmpty();
    }
}
public class LinkedListDemo1 { 
    //输出
    public static void sop(Object obj){
        System.out.println(obj);
    }
 public static void main(String[] args)
    {  
     DuiLie link=new DuiLie();
     link.myAdd("hh0");
     link.myAdd("hh1");
     link.myAdd("hh2");
     link.myAdd("hh3");
     while(!link.isNull())
     {
         sop(link.myGet());
     }
    }
}
package atheima;

import java.util.ArrayList;
import java.util.Iterator;
//将自定义对象作为元素存到ArrayList集合中,并去除重复元素
//比如:存人对象,同姓名同年龄,视为同一个人,为重复元素
//思路:对人描述,将数据封装到人的对象,,定义容器,将人存入,,取出
//结论:list集合判断元素是否相同,依据是元素的equa方法
class Person1
{
    private String name;
    private int age;
    public Person1(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 boolean equals(Object obj) {
        if (!(obj instanceof Person1))
            return false;
        Person1 p1=(Person1) obj;
        return this.name.equals(p1.name)&&this.age==p1.age;        
    }
    
}
public class ArrayListTest2 
{ 
   public static void main(String[] args)
    {  
         ArrayList link=new ArrayList();
         link.add(new Person1("han0", 22));
         link.add(new Person1("han1", 22));
         link.add(new Person1("han2", 23));
         link.add(new Person1("han3", 24));
         link.add(new Person1("han4", 25));
         link.add(new Person1("han4", 25));
         link=singleElement(link);//去除重复的元素
         Iterator it=link.iterator();
         while(it.hasNext())//遍历新的集合元素
         {
             Object obj=it.next();
             Person1 p=(Person1) obj;
             sop(p.getName()+"..."+p.getAge());             
         }
    }
   public static ArrayList singleElement(ArrayList link)
     {
         //定义一个临时容器
         ArrayList newAl=new ArrayList();
         Iterator it= link.iterator();
         //遍历原有的容器
         while(it.hasNext())
         {
             Object obj=it.next();
             if(!newAl.contains(obj))//如果新容器中的元素不包含原有的元素,就添加新的元素进入新容器中。
                 newAl.add(obj);
         }
         return newAl;
     }
     //输出
     public static void sop(Object obj)
     {
         System.out.println(obj);
     }
}

第四讲     Set

一、概述

        Set:元素是无序(存入和取出的顺序不一定一致),元素不可以重复。    

           |--HashSet:底层数据结构是哈希表。线程不同步。 保证元素唯一性的原理:判断元素的hashCode值是否相同。如果相同,还会继续判断元素的equals方法,是否为true。如果不相同,不会判断equals。

           |--TreeSet:可以对Set集合中的元素进行排序。默认按照字母的自然排序。底层数据结构是二叉树。保证元素唯一性的依据:compareTo方法return 0。

        Set集合的功能和Collection是一致的。

二、HasSet

        HashSet:线程不安全,存取速度快。

       可以通过元素的两个方法,hashCode和equals来完成保证元素唯一性。如果元素的HashCode值相同,才会判断equals是否为true。如果元素的hashCode值不同,不会调用equals。

注意:HashSet对于判断元素是否存在,以及删除等操作,依赖的方法是元素的hashCode和equals方法。

package atheima;
import java.util.HashSet;
import java.util.Iterator;
//将自定义对象作为元素存到HashSet集合中,并去除重复元素
//比如:存人对象,同姓名同年龄,视为同一个人,为重复元素
//思路:对人描述,将数据封装到人的对象,,定义容器,将人存入,,取出
class Person2
{
    private String name;
    private int age;
    public Person2(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;
    }    
    public int hashCode()
    {
        System.out.println(this.name+"....hashCode");
        return name.hashCode()+age*39;
    }
    public boolean equals(Object obj)
    {
        if (!(obj instanceof Person2))
            return false;
            Person2 p1=(Person2) obj;
            System.out.println(this.name+"...equals.."+p1.name);
            return this.name.equals(p1.name)&&this.age==p1.age;    
    }
}
public class HashSetTest 
{ 
   public static void main(String[] args)
    {  
         HashSet link=new HashSet();
         link.add(new Person2("han0", 22));
         link.add(new Person2("han1", 22));
         link.add(new Person2("han2", 23));
         link.add(new Person2("han3", 24));
         link.add(new Person2("han4", 25));
         link.add(new Person2("han4", 25));
         Iterator it=link.iterator();
         while(it.hasNext())//遍历新的集合元素
         {
             Object obj=it.next();
             Person2 p=(Person2) obj;
             sop(p.getName()+"..."+p.getAge());             
         }
    }
     //输出
     public static void sop(Object obj)
     {
         System.out.println(obj);
     }
}

三、TreeSet

1、特点

        a、底层的数据结构为二叉树结构

        b)可对Set集合中的元素进行排序,是因为:TreeSet类实现了Comparable接口,该接口强制让增加到集合中的对象进行了比较,需要复写compareTo方法,才能让对象按指定需求(如人的年龄大小比较等)进行排序,并加入集合。

        java中的很多类都具备比较性,其实就是实现了Comparable接口

注意:排序时,当主要条件相同时,按次要条件排序。

 c、保证数据的唯一性的依据:通过compareTo方法的返回值,是正整数、负整数或零,则两个对象较大、较小或相同。相等时则不会存入。

2、TreeSet排序的两种方式

        1)第一种排序方式:自然排序

        让元素自身具备比较性。元素需要实现Comparable接口,覆盖compareTo方法。这种方式也被称为元素的自然顺序,或者叫做默认顺序。

package atheima;
import java.util.Iterator;
import java.util.TreeSet;

import javax.management.RuntimeErrorException;
//将自定义对象作为元素存到TreeSet集合中,对人的年龄进行排序
class Person3 implements Comparable//该接口强制让人具备比较性
{
    private String name;
    private int age;
    public Person3(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 int compareTo(Object obj) {
        if(!(obj instanceof Person3))
            throw new RuntimeErrorException(null, "不是学生对象");
        Person3 p1=(Person3) obj;
        System.out.println(this.name+"...Compareto..."+p1.name);
        if(this.age>p1.age)
            return 1;
            if(this.age==p1.age)//当年龄相同,就需要对名字排序
            {
                return this.name.compareTo(p1.name);
                    
            }
        return -1;
    }
}
public class TreeSetTest 
{ 
   public static void main(String[] args)
    {  
         TreeSet link=new TreeSet();
         link.add(new Person3("han0", 22));
         link.add(new Person3("han1", 22));
         link.add(new Person3("han2", 23));
         link.add(new Person3("han3", 24));
         link.add(new Person3("han4", 25));
         link.add(new Person3("han5", 25));
         Iterator it=link.iterator();
         while(it.hasNext()){
            Object obj=it.next();
            Person3 p1=(Person3) obj;
            sop(p1.getName()+"..."+p1.getAge());
        }
    }
     //输出
     public static void sop(Object obj)
     {
         System.out.println(obj);
     }
}

2)第二种方式:比较器

        当元素自身不具备比较性时,或者具备的比较性不是所需要的。这时就需要让集合自身具备比较性。

        在集合初始化时,就有了比较方式。定义一个比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。

        比较器构造方式:定义一个类,实现Comparator接口,覆盖compare方法。

        当两种排序都存在时,以比较器为主。

package atheima;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

import javax.management.RuntimeErrorException;
//将自定义对象作为元素存到TreeSet集合中,对人的年龄进行排序
class Person3 implements Comparable//该接口强制让人具备比较性
{
    private String name;
    private int age;
    public Person3(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 int compareTo(Object obj) {
        if(!(obj instanceof Person3))
            throw new RuntimeException("不是学生对象");
        Person3 p1=(Person3) obj;
        System.out.println(this.name+"...Compareto..."+p1.name);
        if(this.age>p1.age)
            return 1;
            if(this.age==p1.age)//当年龄相同,就需要对名字排序
            {
                return this.name.compareTo(p1.name);
                    
            }
        return -1;
    }
}
public class TreeSetTest 
{ 
   public static void main(String[] args)
    {  
         TreeSet link=new TreeSet(new MyCompare());
         link.add(new Person3("han02", 27));
         link.add(new Person3("han02", 22));
         link.add(new Person3("han007", 29));
         link.add(new Person3("han09", 24));
         link.add(new Person3("han06", 25));
         link.add(new Person3("han06", 25));
         Iterator it=link.iterator();
         while(it.hasNext()){
            Object obj=it.next();
            Person3 p1=(Person3) obj;
            sop(p1.getName()+"..."+p1.getAge());
        }
    }
     //输出
     public static void sop(Object obj)
     {
         System.out.println(obj);
     }
}
/**
 * 当元素自身不具备比较性,或者具备的比较性不是所需要的,
 * 这时需要让容器自身具备比较性
 * 定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数
 */
class MyCompare implements Comparator
{

    @Override
    public int compare(Object o1, Object o2) {
        Person3 p1=(Person3) o1;
        Person3 p2=(Person3) o2;
        int num=p1.getName().compareTo(p2.getName());
        if(num==0)
        {
            return new Integer(p1.getAge()).compareTo(new Integer(p2.getAge()));
//            if(p1.getAge()>p2.getAge())
//                return 1;
//            if(p1.getAge()==p2.getAge())
//                return 0;
//            return -1;
        }
        return num;
    }
    
}

 泛型类

什么时候定义泛型类?

当类中要操作的引用数据类型不确定的时候,早期定义object来完成扩展。现在定义泛型完成扩展。

package atheima;

import java.util.*;
public class GenericDemo1
{
    public static void main(String[] args) {
        TreeSet<String> a1=new TreeSet<String>(new MyGntenericDemo());
        a1.add("sda");
        a1.add("adad78");
        a1.add("akjd9");
        Iterator<String> it=a1.iterator();
        while(it.hasNext())
        {
            String s2=it.next();//--->泛型后
            System.out.println(s2);
        }
    }
}
class MyGntenericDemo implements Comparator<String>//--->加泛型无需强转
{
    public int compare(String s1,String s2)
    {
        //按升序排,如果降序就把s1、s2互换
        int num= new Integer(s1.length()).compareTo(new Integer(s2.length()));
        if(num==0)
            return s1.compareTo(s2);
        return num;
    }
}
package atheima;
import java.awt.print.Printable;
import javax.xml.namespace.QName;
class Demoo<T>//在类上定义泛型
{
    public void show(T t)
    {
        System.out.println("show:"+t);
    }
    public void print(T t)
    {
        System.out.println("print:"+t);
    }
}
/**
 * 泛型类定义的泛型,在整个类中有效,如果被方法使用,那么泛型
 * 类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了
 * 为了让不同方法可以操作不同类型,而且类型还不确定那么可以
 * 将泛型定义在方法中。
 * 特殊之处:静态方法不可以访问类上定义的泛型
 * 如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。
 * @author Administrator
 *
 */
class Demoo1<T>
{
    public <T>void show(T t)
    {
        System.out.println("show:"+t);
    }
    public <Q>void Print(Q q)
    {
        System.out.println("print:"+q);
    }
    public static <W> void method(W t)
    {
        System.out.println("method:"+t);
    }
}
public class GenericDemo2
{
    public static void main(String[] args) {
//        Demoo<String>d1=new Demoo<String>();//string类型
//        d1.show("kk");
//        d1.print("han");//必须都是String类型
        Demoo1 d2=new Demoo1();
        d2.show("hh");//--1
        d2.show(3);//--2,泛型定义在方法上,类型可以不同
        d2.method("dd");
    }
}

泛型定义在接口上

package atheima;
interface Inter<T>
{
    void show(T t);
}
class InterImp implements Inter<String>//-->明确类型string
{
    public void show(String s1)
    {
        System.out.println("show:"+s1);
    }
}
//不明确类型,使用泛型
class InterImp1<T> implements Inter<T>
{
    public void show(T t) {
        System.out.println("show:"+t);    
    }    
}
public class GenericDemo3
{
    public static void main(String[] args) {
        InterImp i=new InterImp();
        i.show("hahah");
        //定义整形
        InterImp1<Integer>i1=new InterImp1<Integer>();
        i1.show(4);
    }
}

?通配符。也可以理解为占位符

泛型的限定:

?extends E:可以接收E类型或者E的子类型。上限

?super E:可以接收E类型或者E的父类型。下限

package atheima;
import java.util.*;
public class GenericDemo4
{
    public static void main(String[] args) {
        ArrayList<Person0>a1=new ArrayList<Person0>();
        a1.add(new Person0("abc1"));
        a1.add(new Person0("abc2"));
        a1.add(new Person0("abc3"));
        printColl(a1);
        ArrayList<Student>a2=new ArrayList<Student>();
        a2.add(new Student("ab1"));
        a2.add(new Student("ab2"));
        a2.add(new Student("ab3"));
        printColl(a2);
    }
    public static void printColl(ArrayList<? extends Person0>a1)//?不明白类型用通配符
    {
        Iterator<? extends Person0> it=a1.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next().getNme());
        }
    }
}
class Person0
{
    private String name;
    public Person0(String name)
    {
        this.name=name;
    }
    public String getNme()
    {
        return name;
    }
}
class Student extends Person0
{
    public Student(String name) {
        super(name);
    }
}

第五讲     Map集合

一、概述

1、简述:

        Map<K,V>集合是一个接口,和List集合及Set集合不同的是,它是双列集合,并且可以给对象加上名字,即键(Key)

2、特点:

        1)该集合存储键值对,一对一对往里存

        2)要保证键的唯一性。

 二、Map集合的子类

        Map

            |--Hashtable:底层是哈希表数据结构,不可以存入null键null值。该集合是线程同步的。JDK1.0,效率低。

            |--HashMap:底层是哈希表数据结构。允许使用null键null值,该集合是不同步的。JDK1.2,效率高。

            |--TreeMap:底层是二叉树数据结构。线程不同步。可以用于给Map集合中的键进行排序。

        Map和Set很像。其实Set底层就是使用了Map集合。

三、Map集合的常用方法

1、添加

V  put(K key,V value);//添加元素,如果出现添加时,相同的键,那么后添加的值会覆盖原有键对应值,并put方法会返回被覆盖的值。

        void  putAll(Map <? extends K,? extends V> m);//添加一个集合

2、删除

        clear();//清空

        V  remove(Object key);//删除指定键值对

3、判断

        containsKey(Objectkey);//判断键是否存在

        containsValue(Objectvalue)//判断值是否存在

        isEmpty();//判断是否为空

4、获取

        V  get(Object key);//通过键获取对应的值

        size();//获取集合的长度

        Collection<V>   value();//获取Map集合中所有得值,返回一个Collection集合

还有两个取出方法,接下来会逐个讲解:

        Set<Map.Entry<K,V>>  entrySet();  返回此映射中包含的映射关系的 Set 视图。

        Set<K>  keySet();返回此映射中包含的键的 Set 视图。

注:HashMap集合可以通过get()方法的返回值来判断一个键是否存在,通过返回null来判断。

package atheima;
import java.util.*;
public class GenericDemo5
{
    public static void main(String[] args) {
        Map<String, String>map=new HashMap<String, String>();
        //如果出现添加元素,有相同的键,那么后添加的值会覆盖原有的键对应的值,put方法会返回被覆盖的值
        map.put("01", "han1");
        map.put("01", "han5");
        map.put("02", "han2");
        map.put("03", "han3");
        sop(map.containsKey("01"));//--true
        //sop(map.remove("02"));//---han2
        sop(map.get("03"));//---han3
        map.put(null, "han4");//HashMap可以键入空值
        sop(map.get(null));//--han4
        Collection<String>coll=map.values();
        sop(coll);//[han4, han1, han2, han3]
        //获取map集合中的所有的值
        sop(map);//{null=han4, 01=han1, 02=han2, 03=han3}
        
        
    }
    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}


四、Map集合的两种取出方式

        Map集合的取出原理:将Map集合转成Set集合。再通过迭代器取出。

1、Set<K> keySet():将Map中所有的键存入到Set集合。因为Set具备迭代器。所以可以通过迭代方式取出所以键的值,再通过get方法。获取每一个键对应的值。

2、Set<Map.Entry<K,V>>   entrySet():将Map集合中的映射关系存入到Set集合中,而这个关系的数据类型就是:Map.Entry

       其实,Entry也是一个接口,它是Map接口中的一个内部接口。  

package atheima;
import java.util.*;
/**
 * map 集合的两种取出方式
 * 1.keySet:将map中的所有的键存入到set集合,因为set具备迭代器,
 * 所有可以用迭代方式取出所有的键,在根据get方法,获取每一个键对应的值
 * 
 * 2,
 * @author Administrator
 *
 */
public class MapDemo2
{
    public static void main(String[] args) {
        Map<String, String>map=new HashMap<String, String>();
        //如果出现添加元素,有相同的键,那么后添加的值会覆盖原有的键对应的值,put方法会返回被覆盖的值
        map.put("01", "han1");
        map.put("01", "han5");
        map.put("02", "han2");
        map.put("03", "han3");
        //将map集合中的映射关系取出,存入到set集合中
        Set<Map.Entry<String, String>> entrySet=map.entrySet();
        Iterator< Map.Entry<String, String>> it1=entrySet.iterator();
        while(it1.hasNext())
        {
            Map.Entry<String, String> me=it1.next();
            String key=me.getKey();
            String value=me.getValue();
            sop(key+"--"+value);
            
        }
        
        //现获取map集合的所有键的set集合,keyset();
        Set<String> keySet=map.keySet();
        //有了set集合,就可以获取其迭代器
        Iterator<String>it=keySet.iterator();
        while(it.hasNext())
        {
            String key=it.next();
            //有了键就可以通过map集合的get方法获取其对应的值
            String value=map.get(key);
            sop("key:"+key+",value:"+value);
            
        }
        
    }
    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}
package atheima;
import java.util.*;
import java.util.jar.Attributes.Name;
/*
 * 每一个学生都有对应的归属地。 
学生Student,地址String。 
学生属性:姓名,年龄。 
注意:姓名和年龄相同的视为同一个学生。 保证学生的唯一性。  
思路:1、描述学生类 
     2、定义一个Map集合,将学生作为键,地址作为值 
     3、获取Map中的元素 
     */  
class Student0 implements Comparable<Student0>
{
    private String name;
    private int age;
    public Student0(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;
    }
    public String toString()
    {
        return name+":"+age;
    }
    @Override
    public int hashCode() {
        return name.hashCode()+age*34;
    }
    @Override
    public boolean equals(Object obj) {
        if(!(obj instanceof Student0))
            throw new ClassCastException("类型不匹配");
        Student0 s=(Student0)obj;
        return this.name.equals(s.name)&&this.age==s.age;
    }
    @Override
    public int compareTo(Student0 o) {
        int num=new Integer(this.getAge()).compareTo(new Integer(o.getAge()));
        if(num==0)
            return this.getName().compareTo(o.getName());
        return num;
    }
    
}
public class MapTest
{
    public static void main(String[] args) {
        HashMap<Student0,String>hm=new HashMap<Student0, String>();
        hm.put(new Student0("han1", 18),"beijing");
        hm.put(new Student0("han2", 34),"nanjing");
        hm.put(new Student0("han3", 42),"shangqiu");
        hm.put(new Student0("han4", 12),"nanyang");
        //第一种取出方式keySet
        Set<Student0>keySet=hm.keySet();
        Iterator<Student0>it=keySet.iterator();
        while(it.hasNext())
        {
            Student0 s1=it.next();
            String address=hm.get(s1);
            sop(s1+":"+address);
            
        }
        //第二种取出方式Map.Entry
        Set<Map.Entry<Student0, String>>enterSet=hm.entrySet();
        Iterator<Map.Entry<Student0, String>>it1=enterSet.iterator();
        while(it1.hasNext())
        {
            Map.Entry<Student0, String> entry=it1.next();
            Student0 stu1=entry.getKey();
            String s1=entry.getValue();
            sop(stu1+"...."+s1);
        }
        
    }
    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}
package atheima;
import java.util.*;
import java.util.jar.Attributes.Name;
/*
需求:对学生对象的年龄进行升序排序
因为数据是以键值对形式存在的
所以要使用可以排序的map集合---》TreeMap
*/  
class Student4 implements Comparable<Student4>
{
    private String name;
    private int age;
    public Student4(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;
    }
    public String toString()
    {
        return name+":"+age;
    }
    @Override
    public int hashCode() {
        return name.hashCode()+age*34;
    }
    @Override
    public boolean equals(Object obj) {
        if(!(obj instanceof Student4))
            throw new ClassCastException("类型不匹配");
        Student4 s=(Student4)obj;
        return this.name.equals(s.name)&&this.age==s.age;
    }
    @Override
    public int compareTo(Student4 o) {
        int num=new Integer(this.getAge()).compareTo(new Integer(o.getAge()));
        if(num==0)
            return this.getName().compareTo(o.getName());
        return num;
    }
    
}
//自定义集合按姓名排序
class MyCompar implements Comparator<Student4>
{
    @Override
    public int compare(Student4 o1, Student4 o2) {
        int num=o1.getName().compareTo(o2.getName());
        if(num==0)
            return new Integer(o1.getAge()).compareTo(new Integer(o2.getAge()));
        return num;
    }
}
public class MapTest1
{
    public static void main(String[] args) {
        TreeMap<Student4,String>hm=new TreeMap<Student4, String>(new MyCompar());
        hm.put(new Student4("han1", 18),"beijing");
        hm.put(new Student4("ahan2", 34),"nanjing");
        hm.put(new Student4("chan3", 42),"shangqiu");
        hm.put(new Student4("jhan4", 12),"nanyang");
        
        Set<Map.Entry<Student4, String>>enterSet=hm.entrySet();
        Iterator<Map.Entry<Student4, String>>it1=enterSet.iterator();
        while(it1.hasNext())
        {
            Map.Entry<Student4, String> entry=it1.next();
            Student4 stu1=entry.getKey();
            String s1=entry.getValue();
            sop(stu1+"...."+s1);
        }
        
    }
    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}
package atheima;
import java.util.*;
/*
 * 练习:sdfgxxvasdfxcvdf获取该字符串中的字母出现的次数
 * 结果:a(1)c(2)...
 * 通过结果发现,每一个字母都有对应的次数,说明字母和次数之间
 * 都有映射关系---》选择map集合,因为map集合中存放的就是映射关系。
 * 思路:
 * 1.将字符串转换为字符数组,因为要对每一个字母进行操作
 * 2,定义一个map集合,因为打印结果的字母有顺序,所以使用treemap集合
 * 3.遍历字符数组
 *   将每一个字母作为键去查map集合
 *   如果返回null将该字母和1存入到map集合中
 *   如果返回不是null,说明该字母在map集合已经存在并有对应次数
 *   那么就获取该次数并进行自增,然后将该字母和自增后的次数存入到map集合中,覆盖调用原来键所对应的值
 *   4.将map集合中的数据变成指定的字符串形式返回。
*/  
public class MapTest2
{
    public static void main(String[] args) {
        String s=charCount("sdfgxxvasdfxcvdf");
    }
    //定义一个方法获取字符串中字母出现的次数 
    public static String charCount(String str) {
        char[] cha=str.toCharArray();//转换为字符数组  
         //定义一个TreeMap集合,因为TreeMap集合会给键自动排序  
        TreeMap<Character, Integer>tm=new TreeMap<Character, Integer>();
        int count=0;//定义计数变量
        for(int x=0;x<cha.length;x++)
        {
            if(!(cha[x]>='a'&&cha[x]<='z'||cha[x]>='A'&&cha[x]<='Z'))
                continue;//如果字符串中非字母,则不计数  
            Integer values=tm.get(cha[x]);//获取集合中的值  
            if(values!=null)//如果集合中没有该字母,则存入  
                count=values;
            count++;
            tm.put(cha[x], count);//存入键值对  
            count=0;//复位计数变量  
        }
        StringBuilder sb=new StringBuilder();//定义一个容器
        Set<Map.Entry<Character, Integer>> entry=tm.entrySet();
        Iterator<Map.Entry<Character, Integer>>it=entry.iterator();
        while(it.hasNext())
        {
            Map.Entry<Character, Integer> me=it.next();
            Character key=me.getKey();
            Integer values=me.getValue();
            sb.append(key+"("+values+")");
        }
        System.out.println(sb);
        return null;
    }
}
package atheima;
import java.util.*;
/* 
map扩展知识。 
map集合被使用是因为具备映射关系。 
以下是班级对应学生,而学生中学号对应着姓名的映射关系: 
"yureban"   Student("01" "zhangsan");  
"yureban" Student("02" "lisi");  
"jiuyeban" "01" "wangwu"; 
"jiuyeban" "02" "zhaoliu";  
就如同一个学校有多个教室。每一个教室都有名称。 
*/  
public class MapTest3//第一种方法
{
    public static void main(String[] args) 
    {
        //传智博客学校对应的集合:键为:班级,值为:学生其中学生又是一个集合包含学号和姓名
    HashMap<String, HashMap<String, String>>czbk=new HashMap<String, HashMap<String,String>>();
    //预热班级集合对应的键是学号,值为姓名
    HashMap<String, String>yure=new HashMap<String, String>();
    //就业班级集合对应的键是学号,值为姓名
    HashMap<String, String>jiuye=new HashMap<String, String>();
    //传智播客班级集合和名称的映射
    czbk.put("yureban", yure);
    czbk.put("jiuyeban", jiuye);
    //预热班级中学号与姓名的映射  
    yure.put("01","zhangsan" );
    yure.put("02", "lisi");
    //就业班级中学号与姓名的映射 
    jiuye.put("01", "wangwu");
    jiuye.put("02", "zhaoliu");
    //遍历czbk集合,获取所有的教室
    Iterator<String>it=czbk.keySet().iterator();
    while(it.hasNext())
    {
        String roomName=it.next();
        HashMap<String, String> room=czbk.get(roomName);
        System.out.println(roomName);
        getStudentInfo(room);
    }
    }
    public static void getStudentInfo(HashMap<String, String> roomMap)//变量为班级
    {
        Iterator<String>it=roomMap.keySet().iterator();//用keySet取出方式 
        while(it.hasNext())
        {
            String id=it.next();
            String name=roomMap.get(id);
            System.out.println(id+":"+name);
            
        }
    }
}
package atheima;
import java.util.*;
/* 
map扩展知识。 
map集合被使用是因为具备映射关系。 
以下是班级对应学生,而学生中学号对应着姓名的映射关系: 
"yureban"   Student("01" "zhangsan");  
"yureban" Student("02" "lisi");  
"jiuyeban" "01" "wangwu"; 
"jiuyeban" "02" "zhaoliu";  
就如同一个学校有多个教室。每一个教室都有名称。 
*/  
class Students//第二种方法常用到
{
    private String id;
    private String name;
    public Students(String id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    @Override
    public String toString() {
        return "Students [id=" + id + ", name=" + name + "]";
    }
}
public class MapTest4
{
    public static void demo()
    {
        HashMap<String, List<Students>>czbk=new HashMap<String, List<Students>>();
        List<Students> yure=new ArrayList<Students>();//yure班
        List<Students> jiuye=new ArrayList<Students>();//jiuye班
        czbk.put("yureban", yure);
        czbk.put("jiuyeban", jiuye);
        yure.add(new Students("03","han3"));
        yure.add(new Students("04","han4"));
        jiuye.add(new Students("03","han3"));
        jiuye.add(new Students("04","han4"));
        Iterator<String>it=czbk.keySet().iterator();
        while(it.hasNext())
        {
            String roomName=it.next();
            List<Students> room=czbk.get(roomName);
            System.out.println(roomName);
            getInfos(room);
        }
    }
    public static void getInfos(List<Students>list)
    {
        
        Iterator<Students>it1=list.iterator();
        while(it1.hasNext())
        {
            Students room=it1.next();
            System.out.println(room);
        }
    }
    public static void main(String[] args) 
    {
        demo();
    }
    public static void getStudentInfo(HashMap<String, String> roomMap)//变量为班级
    {
        Iterator<String>it=roomMap.keySet().iterator();//用keySet取出方式 
        while(it.hasNext())
        {
            String id=it.next();
            String name=roomMap.get(id);
            System.out.println(id+":"+name);
            
        }
    }
}
原文地址:https://www.cnblogs.com/Hanxia/p/4513197.html