黑馬程式員—java基礎——————集合架構2—Map

來源:互聯網
上載者:User

 

Map<k,v>:索引值對的映射關係,鍵是唯一的。

   |hashtable:底層是雜湊表資料結構,不可以存入null值null鍵,同步的(1.0)

   |--treeMap:底層是二叉樹,線程不同步,可以用於給Map集合中的鍵排序。

Map的共性方法:

    1:添加:

        put(k,v)

        putAll(Map<? extends k,<? extends v>m)

    2:刪除:

        clear()

    3:判斷:

        containsKey(Object key)

        containsValue(Object Value)

        isEmpty()

    4:擷取:

        get(Object key)

        size()

        values()

        entrySet()

        keySet()

import java.util.*;
class Demo
{
     public static void main(String[] args)
     {
        Map<String,String> map=new HashMap<String,String>();
        map.put("01","zhangsan1");//添加時相同的鍵,後添加的值,後添加會覆蓋原有的值,並put方法會返回被覆蓋的值
        map.put("02","zhangsan2");
        map.put("03","zhangsan3");
        System.out.println(map.containsKey("012"));   //false
        System.out.println(map.remove("02"));    //返回(刪除後)zhangsan2
        System.out.println(map.get("01"));     //擷取zhangsan1,可以用傳回值來判斷一個鍵是否存在,通過返回null來判斷
        map.put("04",null);      //添加成功,但是hashtable是不可以的
        Collection<String> coll = map.values();
        System.out.println(coll);    //[null,zhangsan1,zhangsan3]
     }
}

import java.util.*;

class Demo {  

    public static void main(String[] args)  {   

      //通過拿到所有的鍵拿到所有的值,他沒有迭代器keySet(),set也就是集合,   //它具備迭代器,可以用迭代去除所有的鍵,再擷取值   

      Map<String,String> map=new HashMap<String,String>();   

      map.put("01","zhangsan1");map.put("04","zhangsan2");   map.put("02","zhangsan2");   map.put("03","zhangsan3");   

      Set<String> keyset=map.keySet();   

      Iterator<String> it=keyset.iterator();   

      while(it.hasNext())   {    

          String key=it.next();    

          String values=map.get(key);    

          System.out.println(key+"::"+values);   }

        //Set<Map.Entry<k,v>> entrySet,取出的第二種方式,它取出的是映射關係返回的是Map.Entry   

      Set<Map.Entry<String,String>> entrySet=map.entrySet();   //也是返回一個SEt集合   

      Iterator<Map.Entry<String,String>> it1=entrySet.iterator();   

      while(it1.hasNext())   {    

          Map.Entry<String,String> me=it1.next();//看API這個對象Map.Entry鎖對應的類型    

          String key=me.getKey();    

          String values=map.get(key);    

          System.out.println(key+"::"+values);   

      }  

  }

}

練習:將學生Object Storage Service到集合中,同名同年齡為一個學生,如果是存在雜湊表結構中會怎麼樣,存在二叉樹結構中的情況

import java.util.*;

class Student implements compareable<Student>

{

  private  String name;

  private int age;

  Student(String name,int age)

  {

      this.name=name;

      this.age=age;

  }

  public String getName()

  {

    return name;

  }

  public int getAge()

  {

    return age;

  }

  public String toString()

  {

    return   name+"::"+age;

  }

  /*這種情況是存在雜湊表結構集合中*/

  public int hashCode()

  {

    return name.hashCode()+age*32;//age乘以一個數是保證了hash值的唯一性

  }

  public boolean equals(Object   obj)

  {

    if(!(obj instansOf Student))

      throw new ClassCastException("類型轉換異常");

    Student  s= (Student)obj;

      return this.name.equals(s.name) && this.age=s.age;

  }

  /*這種情況是存在二叉樹集合中,要讓它具備自然順序,要實現compareable*/

  public int compareaTo(Student  s)

  {

    int num=new Integer(this.age).compareTo (new Integer(s.age));

    if(num==0)

      return this.name.compareTo(s.name);

    return  num;

}

class  MapTest

{

  public static void main(String[] args)

  {

    HashMap<Student,String> hm=new HashMap<Studeng,String>

    hm.put(new Student("lisi1",21),"beijin");

    hm.put(new Student("lisi2",22),"shanghai");

    hm.put(new Student("lisi2",22),"shanxi");//鍵不唯一但是複寫了上面的兩個方法還是可以的

    hm.put(new Student("lisi3",23),"tianjin");

    hm.put(new Student("lisi4",24),"wuhan");

    //第一種取出方式

    Set<Student>   keySet=hm.keySet();

    Iterator<Student> it=keySet.iterator();

    while(it.hasNext())

    {  

      Student stu=it.next();

      String   adrr=hm.get(stu);

      System.out.println(stu+"::"+adrr);

    }

    //第二種取出方式entrySet

    Set<Map.Entry<Student,String>> entrySet=hm.entrySet();

    Iterator<Map.Entry<Student,String>>   iter=entrySet.iterator();

    while(iter.hasNext())

    {  

      Map.Entry<Student,String>   me=iter.next();

      Student stu=me.getkey();

      String adrr=hm.get(stu);

      System.out.println(stu+"::"+adrr);

    }

  } 

}

class  MapTest2   //這個方法可以實現自然排序

{

  public static void main(String[] args)

  {

    TreeMap<Student,String> tm=new TreeMap<Studeng,String>

    tm.put(new Student("lisi1",21),"beijin");

    tm.put(new Student("lisi2",22),"shanghai");

    hm.put(new Student("lisi2",22),"shanxi");//鍵不唯一但是複寫了上面的兩個方法還是可以的

    tm.put(new Student("lisi3",23),"tianjin");

    tm.put(new Student("lisi4",24),"wuhan");

    //第二種取出方式entrySet

    Set<Map.Entry<Student,String>> entrySet=tm.entrySet();

    Iterator<Map.Entry<Student,String>> iter=entrySet.iterator();

    while(iter.hasNext())

    {  

      Map.Entry<Student,String>   me=iter.next();

      Student stu=me.getkey();

      String adrr=hm.get(stu);

      System.out.println(stu+"::"+adrr);

    }

  } 

}

//自訂個按姓名排序的比較子,傳給調用函數

class  StuNameComparator  implements Comparator<Student>

{

  public int  compare(Student  s1,Student  s2)

  {

    int num=s1.getName().comparaTo(s2.getName());//姓名比較相同的情況下,砸U按次要條件年齡排序,如果年齡還相等就不能添加

    if(num==0)

      return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));

    return num;

  }

}

map集合的擴充:集合嵌套:傳智播客和班級是個集合,班級和學生又是一個集合

集合工具類:

    Collection是集合架構中的一個頂層介面,它裡面定義了單列集合的共性方法。它有兩個常用的子介面,List:對元素都有定義索引。有序的。可以重複元素。Set:不可以

          重複元素。無序。

    Collections是集合架構中的一個工具類。該類中的方法都是靜態提供的方法中有可以對list集合進行排序,二分尋找等方法。通常常用的集合都是線程不安全的。因為要提

          高效率。如果多線程操作這些集合時,可以通過該工具類中的同步方法,將線程不安全的集合,轉換成安全的。

    Collection介面中的toArray方法

        指定類型的數組到底要定義多長呢?:當指定類型的數組長度小於了集合的size,那麼該方法內部會建立一個新的數組。長度為集合的size。當指定類型的數組長度  

            大於了集合的size,就不會新建立了數組。而是使用傳遞進來的數組。所以建立一個剛剛好的數組最優。

        為什麼要將集合變數組?:為了限定對元素的操作。不需要進行增刪了。        

        ArrayList<String> al = new ArrayList<String>();

          al.add("abc1");   al.add("abc2");   al.add("abc3");

        String[] arr = al.toArray(new String[al.size()]);

    asList:將數組變成list集合       

        把數組變成list集合有什麼好處?:可以使用集合的思想和方法來運算元組中的元素。 注意:將數組變成集合,不可以使用集合的增刪方法,因為數組的長度是固

            定的。否則會發生UnsupportedOperationException。

            如果數組中的元素都是對象。那麼變成集合時,數組中的元素就直接轉成集合中的元素。如果數組中的元素都是基礎資料型別 (Elementary Data Type),那麼會將該數組作為集合中

            的元素存在。

        String[] arr = {"abc","cc","kkkk"};

        List<String> list = Arrays.asList(arr);   //這邊都是有泛型的

增強for迴圈:只能擷取集合元素。但是不能對集合進行操作。

    for(資料類型 變數名 : 被遍曆的集合(Collection)或者數組)
    {
 
    }

    ArrayList<String> al = new ArrayList<String>();             al.add("abc1");            al.add("abc2");       al.add("abc3");

    for(String s : al)

    {

        System.out.println(s);

    }

可變參數(類型...args):可變參數一定要定義在參數列表最後面。

public static void show(String str,int... arr)

{

    System.out.println(arr.length);

}

靜態匯入:當類名重名時,需要指定具體的包名。當方法重名是,指定具備所屬的對象或者類。

    import static  java.util.Arrays.*;

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.