1. 程式人生 > >雙列集合Map及實現該接口的類的常用方法

雙列集合Map及實現該接口的類的常用方法

mat 是否 商務 bool d+ 其他 val 編號 依賴

為什麽要學雙列集合?

因為單列集合無法處理映射關系,會有成對出現的數據

Map接口 如果是實現了Map接口的集合類,具備的特點: 存儲的數據都是以鍵值對的形式存在的,鍵不可重復,值可以重復

  Map接口的方法:
    添加:
       put(K key, V value)
       putAll(Map<? extends K,? extends V> m)
     刪除
      remove(Object key)
       clear()

     獲取:
       get(Object key)
       size()
     判斷:
       containsKey(Object key)
       containsValue(Object value)
       isEmpty()

    叠代:
      keySet()
      values()
       entrySet()

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

public class Demo1 {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<String,String>();
        //添加
        map.put("李傑","李英");
        map.put(
"黎晨輝","王成娟"); map.put("蠻王","艾希"); map.put("zhangsan", "999999"); System.out.println(map.put("蠻王", "寡婦"));//寡婦把艾希替換了返回艾希,被替換的 System.out.println(map.put("zhangsan", "value"));//如果前面沒有添加就返回null System.out.println(map); Map<String,String> map1 = new HashMap<String,String>(); map1.put(
"文章", "馬伊琍"); map1.put("謝霆鋒","張柏芝"); map1.put("成龍", "林鳳嬌"); map.putAll(map1); System.out.println(map); //刪除 //System.out.println("被刪除的數據: "+map.remove("蠻王"));//根據鍵值刪除數據,返回的是刪除的建對應的值 //System.out.println(map); //map.clear(); //System.out.println(map); //獲取 System.out.println(map.get("蠻王"));//根據指定的建獲取值 System.out.println(map.size());//鍵值對個數 //判斷 System.out.println(map.containsKey("蠻王"));//判斷集合是否包含指定的建 System.out.println(map.containsValue("張柏芝"));//判斷集合是否包含指定的值 System.out.println(map.isEmpty()); } }
//雙列集合沒有叠代器,所以在遍歷雙列集合的時候要返回單列集合,然後借用單列集合的叠代器
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Demo2 {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<String,String>();
        map.put("李傑","李英");
        map.put("黎晨輝","王成娟");
        map.put("蠻王","艾希");
        /*
        //map集合中遍歷方式一: 使用keySet方法進行遍歷       缺點: keySet方法只是返回了所有的鍵,沒有值
        Set<String> keysView = map.keySet(); 
        System.out.println(keysView);
        
        //keySet() 把Map集合中的所有鍵都保存到一個Set類型 的集合對象中返回。
        Iterator<String> it = keysView.iterator();
        while(it.hasNext()) {
            //System.out.println(it.next());
            String list = it.next();
            System.out.print("{鍵:"+list+",值:"+map.get(list)+"}");
            System.out.println();
        }
        
        //map集合的遍歷方式二: 使用values方法進行 遍歷    缺點: values方法只能返回所有 的值,沒有鍵
        Collection<String> valuesView = map.values();
        System.out.println(valuesView);
        Iterator<String> ir = valuesView.iterator();
        while(ir.hasNext()) {
            System.out.print(ir.next()+"   ");
        }
        */
        //map集合的遍歷方式三: entrySet方法遍歷
        Set<Map.Entry<String,String>> entrylist = map.entrySet();
        Iterator<Map.Entry<String,String>> io = entrylist.iterator();
        while(io.hasNext()){
            Map.Entry<String,String> entry = io.next();
            System.out.println("鍵:"+ entry.getKey()+" 值:"+ entry.getValue());
        }
    }
}

HashMap和TreeMap和Hashtable(了解)

  HashMap 底層也是基於哈希表實現 的。
    HashMap的存儲原理:
      往HashMap添加元素的時候,首先會調用鍵的hashCode方法得到元素 的哈希碼值,然後經過運算就可以算出該
       元素在哈希表中的存儲位置
      情況1: 如果算出的位置目前沒有任何元素存儲,那麽該元素可以直接添加到哈希表中


      情況2:如果算出 的位置目前已經存在其他的元素,那麽還會調用該元素的equals方法與這個位置上的元素進行比較
      ,如果equals方法返回 的是false,那麽該元素允許被存儲,如果equals方法返回的是true,那麽該元素被視為
       重復元素,不允存儲

import java.util.HashMap;

class person{
     int id;
     String name;
     
     public person(int id, String name) {
            super();
            this.id = id;
            this.name = name;
     }
     
    public String toString() {
        return  "[編號:"+this.id+" 姓名:"+ this.name+"]";
    }
    
    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return this.id;
    }
    @Override
    public boolean equals(Object obj) {
        person p = (person) obj;
        // TODO Auto-generated method stub
        return this.id == p.id;
    }
}

public class Demo3 {
    public static void main(String[] args) {
        HashMap<person,String> map = new HashMap<person,String>();
        map.put(new person(110,"李傑"), "lalala");
        map.put(new person(120,"李英"), "hahaha");
        map.put(new person(119,"李漢斯"), "xixixi");
        map.put(new person(119,"李漢斯"), "qiqiqi");
        System.out.println(map);
    }    
}

  TreeMap TreeMap也是基於紅黑樹(二叉樹)數據結構實現的 特點:會對元素的鍵進行排序存儲

    TreeMap 要註意的事項:
      1.往TreeMap添加元素的時候,如果元素的鍵具備自然順序,那麽就會按照鍵的自然順序特性進行排序存儲
      2.往TreeMap添加元素的時候,如果元素的鍵不具備自然順序特性, 那麽鍵所屬的類必須要實現Comparable接口,把鍵
        的比較規則定義在CompareTo方法上

      3. 往TreeMap添加元素的時候,如果元素的鍵不具備自然順序特性,而且鍵所屬的類也沒有實現Comparable接口,那麽就必須
       在創建TreeMap對象的時候傳入比較器

import java.util.Comparator;
import java.util.TreeMap;

class Person {
    String name;
    int salary;
    public Person( String name,int salary) {
        super();
        this.name = name;
        this.salary = salary;
    }
    @Override
    public String toString() {
        return "[姓名:"+this.name+" 薪水:"+ this.salary+"]";
    }    
}

class mycompare implements Comparator<Person>{

    @Override
    public int compare(Person o1, Person o2) {
        // TODO Auto-generated method stub
        return o1.salary - o2.salary;
    }
    
}

public class Demo3 {
    public static void main(String[] args) {
        
        /*TreeMap<Character, Integer> tree = new TreeMap<Character, Integer>();
        tree.put(‘c‘,10);
        tree.put(‘b‘,2);
        tree.put(‘a‘,5);
        tree.put(‘h‘,12);
        System.out.println(tree);*/
        TreeMap<Person,Integer> tree = new TreeMap<Person,Integer>(new mycompare());
        tree.put(new Person("李傑",110), 001);
        tree.put(new Person("李英",120), 002);
        tree.put(new Person("李漢斯",119), 003);
        System.out.println(tree);        
        
    }
}
import java.util.Comparator;
import java.util.TreeMap;

class Person implements Comparable{
    String name;
    int salary;
    public Person( String name,int salary) {
        super();
        this.name = name;
        this.salary = salary;
    }
    @Override
    public String toString() {
        return "[姓名:"+this.name+" 薪水:"+ this.salary+"]";
    }
    
    @Override
    public int compareTo(Object o) {
        Person a = (Person) o;
        return this.salary - a.salary;
    }
    
}

public class Demo3 {
    public static void main(String[] args) {
        
        /*TreeMap<Character, Integer> tree = new TreeMap<Character, Integer>();
        tree.put(‘c‘,10);
        tree.put(‘b‘,2);
        tree.put(‘a‘,5);
        tree.put(‘h‘,12);
        System.out.println(tree);*/
        TreeMap<Person,Integer> tree = new TreeMap<Person,Integer>();
        tree.put(new Person("李傑",110), 001);
        tree.put(new Person("李英",120), 002);
        tree.put(new Person("李漢斯",119), 003);
        System.out.println(tree);        
        
    }
}

作業: 定義一個TreeMap,鍵存儲的是書對象,值存儲的是字符串。 根據書的出版出版日期排序

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeMap;

class Book<T> implements Comparable<Book>{
    
    String name;
    String date; 
    public Book(String name,String string) {
        super();
        this.name = name;
        this.date = string;
    }
    /*
    @Override
    public int compareTo(Book o) {
        
        return this.date.compareTo(o.date);
    }
    */
    public int compareTo(Book o) {
        SimpleDateFormat dataformat = new SimpleDateFormat("yyyy-mm-dd");
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = dataformat.parse(this.date);
            date2 = dataformat.parse(o.date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        return date1.compareTo(date2);
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "{書名:"+this.name+"出版日期:"+this.date+",出版社:}";
    }
}

public class Demo4 {
    
    public static void main(String[] args) {
        TreeMap<Book, String>  map = new TreeMap<Book, String>();  //值存儲書名
        map.put(new Book("《紅樓夢》","2018-7-25"), "商務出版社");
        map.put(new Book("《西遊記》","2018-7-26"), "商務出版社");
        map.put(new Book("《水滸傳》","2018-7-27"), "商務出版社");
        map.put(new Book("《三國演義》","2018-7-28"), "商務出版社");
        System.out.println(map);
    }

}

HashTable 底層依賴哈希表存在的,實現方式與HashMap一直,但是他是線程安全的,操作效率低





雙列集合Map及實現該接口的類的常用方法