天天看点

第51节:Java当中的集合框架Map

第51节:Java当中的集合框架Map
简书作者:达叔小生

Java当中的集合框架Map

01

​Map​

​提供了三个集合视图:

  1. 键集
  2. 值集
  3. 键-值 映射集
public String getWeek(int num){
 if(num<0 || num>7){
  throw new NoWeekException(num+"没有对应的星期");
  String[] weeks = {"","星期一"...."星期日"};
  return weeks[num];
 }
}
      

​Sunday​

​(星期天)、​

​Monday​

​(星期一)、​

​Tuesday​

​(星期二)、​

​Wednesday​

​(星期三)、​

​Thursday​

​(星期四)、​

​Friday​

​(星期五)、​

​Saturday​

​(星期六)

java.util
接口 Map<K,V>
参数:
K为此映射的键
V为此映射的值
      

知道的子接口:

Bindings,ConcurrentMap<K,V>,ConcurrentNavigableMap<K,V>,LogicalMessageContext,MessageContext,NavigableMap<K,V>,SOAPMessageContext,SorteMap<K,V>
      

知道的实现类:

AbstractMap,Attributes,AuthProvider,ConcurrentHashMap,ConcurrentSkipListMap,EnumMap,HashMap,Hashtable,IdentityHashMap,LinkedHashMap,PrinterStateReasons,Properties,Provider,RenderingHints,SimpleBindings,TabularDataSupport,TreeMap,UIDefaults,WeakHashMap
      

实现的接口:

public interface Map<K,V>
      
在映射中不能有重复的键,每个键只能映射在一个值上

在​

​Map​

​集合中的特点:

  1. 内部存储的模式是以键-值对的形式
  2. ​Map​

    ​中的键要具有唯一性

嵌套类(内部的):

方法 说明
Map.Entry<K,V>

​static interface​

​,静态 接口,映射模式键-值对

Map方法:

​clear()​

类型为​

​void​

​,在映射中移除所有的映射关系

​containsKey(Object key)​

返回​

​boolean​

​类型,如果映射中包含指定的键的映射关系,返回为​

​true​

​,反之为​

​false​

​containsValue(Object value)​

​boolean​

​类型,如果映射中一个或多个键映射到指定的值上,返回为​

​true​

​false​

​entrySet()​

返回类型为​

​Set<Map.Entry<K,V>>​

​ 返回此映射中包含的映射关系

​equals(Object o)​

​boolean​

​,比较指定对象与映射是否相等

​get(Object key)​

返回值,返回指定键所映射的值,如果此映射不包含该键的映射关系,返回为​

​null​

​,代表没有

​hasCode()​

返回为​

​Int​

​类型,返回此映射的哈希码值

​isEmpty()​

​boolean​

​,如果此映射没有键-值的映射关系,返回为​

​true​

​false​

​keySet()​

​Set<E>​

​,返回此映射中包含的所有键的​

​Set​

​视图

​put(K key, V value)​

将对应的键与值,建立映射关系,添加映射关系的方法

​putAll(Map<? extends K, ? extends V> m)​

​void​

​,从指定的映射关系中将所有的映射关系复制到此映射中

​remove(Object key)​

如果存在这个键的映射关系就将其移除

​size()​

​Int​

​类型,返回此映射关系中的键-值映射关系的数目

​values()​

​Collection<V>​

​,返回此映射中包含的值的​

​Collection​

​put​

V put (E key, V value)
      

将对应的键与值,建立映射关系,添加映射关系的方法,如果之前就有这个映射关系,就会将指定的值替换掉旧的值。

参数:

​key​

​ - 为指定的关联的键

​value​

​ - 为指定的关联的值

会抛出的错误:

UnsupportedOperationException:不支持put操作
ClassCastException:不允许用映射关系
NullPointerException:将指定的键或者值为null,而此映射却不允许存储
IllegalArgumentException:指定的键或者值不允许存储到映射中
      

一般用的实现类:

​HashMap​

java.util
类 HashMap<K,V>
java.lang.Object
 -> java.util.AbstractMap<K,V>
  -> java.util.HashMap<K,V>
      
K-为所对应的键
V-为所对应的值
      

已实现的接口:

Serializable,Cloneable,Map<K,V>
      

已知的子类:

LinkedHashMap,PrinterStateReasons
      

所以:

public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
      

02

​Map​

​例子:
import java.util.HashMap;
public class MapDemo {
 public static void main(String[] args){
  // 建立map
  Map<String,String> map = new HashMap<String,String>();
 // 添加元素
  map.put("星期一", "Monday");
  mpa.put( ...// 自行添加 );
  map.put("星期日", "Sunday");
  // 添加元素时,如果键相同,值会覆盖
  map.put("星期日", "SundayDemo");  // 值被覆盖
 // 获取值
 String value = map.get("星期日"); // 键存在,返回值,反之返回null,为空
 // 删除元素
 String s = map.remove("星期日"); // 删除对应的键值对关系,这样在Map集合中就少了这一对键值对
 }
}
      
如何获取所有的键
Map<String,String> map = new HashMap<String,String>();
map.put("星期一", "Monday");
map.put("星期日", "Sunday");
      

使用​

​keySet​

Set<String> keySet = map.keySet();
for(Iterator<String> it = keySet.iterator(); it.hasNext(); ){
 String key = it.next();
 String value = map.get(key);
 System.out.println(key + " : " + value);
}
      

可以使用​

​foreach​

​循环

for(String key : keySet){
 System.out.println(key + " = " + map.get(key));
}
      

​entrySet​

Set<Map.Entry<K,V>> entrySet()
      

作用为返回此映射中包含的映射关系​

​Set​

​的视图,将​

​map​

​集合中映射关系存储到​

​set​

​集合中。

映射关系:指键和值对应的关系,数据类型​

​Map.Entry​

​(内部的)关系的类型

Set<Map.Entry<String,String>> entrySet = map.entrySet();
Iterator< Map.Entry<String,String> > it = entrySet.iterator();
while(it.hasNext(K,V)){
 Map.Entry<String,String> m = it.next();
 // 获取键
 String key = m.getKey();
 // 获取值
 String value = m.getValue();
 System.out.println(key + " : " + value);
}
      

​Map.Entry<K,V>​

java.util
接口 Map.Entry<K,V>
      

接口实现类:

AbstractMap.SimpleEntry , AbstractMap.SimpleImmutableEntry
      

接口:

public static interface Map.Entry<K,V>
// 为映射项 - 键-值 对
      

​Map.Entry<K,V>​

​方法

方法:

​equals(Object o)​

​boolean​

​,比较指定对象与此项的相等性

​getKey()​

返回为此项对应的键

​getValue()​

返回为此项对应的值

​hashCode()​

​int​

​,返回为此项的哈希码值

​setValue(V value)​

用指定的值去换此项对应的值
for(Map.Entry<String,String> m : map.entrySet()){
 String key = m.getKey();
 String value = m.getValue();
 System.out.println(key + " : " + value);
}
      
interface Map{
 public static interface Entry();
}
      

​values()​

​Collection<V>​

​Collection​

Collection<String> values = map.values();
for(String value : values){
 System.out.println("value:"+value);
}
      
总结:​

​Map -> entrySet() getKey() getValue() -> keySet() get(key) -> values()​

03

第51节:Java当中的集合框架Map

​Hashmap​

public class HashMapDemo {
 public static void main(String[] args){
  Map<Student,String> map = new HashMap<Student,String>();
 // 添加元素
 map.put(new Student("da",12), "1");
 map.put(new Student("shu",13), "2");
 map.put(new Student("dashu",14), "3");
 // 取出数据
 // Set<Student> keySet = map.keySet();
 // for(Student key : keySet){}
 for(Student key : map.keySet() ){
  String value = map.get(key);
  System.out.println(key.toString() + " : " + value);
 }
 }
}
      
public class Student implements Comparable<Student>{
 private String name;
 private int age;
 public Student(){
  super();
 }
 public Student(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 String toString() {
  return "Student [name = " + name +",age = " + age + "]";
 }
 @Override
 public int hasCode() {
  final int prime = 31;
  int result = 1;
  result = prime + result + age;
  result = prime + result + ((name == null) ? 0 : name.hashCode());
  return result;
 }
 @Override
 public boolean equals(Object obj){
  if(this == obj)
   return true;
  if(obj == null)
   return false;
  if(getClass() != obj.getClass() )
   return false;
  Student other = (Student) obj;
  if(age != other.age)
   return false;
  if(name == null){
   if(other.name != null)
    return false;
  }else if(!name.equals(other.name))
    return false;
  return true;
 }
 @Override
 public int  compareTo(Student o){
  int temp = this.age - o.age;

  return temp == 0? this.name.compareTo(o.name) : temp;
 }
}
      

​TreeMap​

public class TreeMapDemo{
 public static void main(String[] args){
   Map<Student, String> map = new TreeMap<Student, String>(new ComparatorByName());
 // 添加元素
 map.put(new Student("da",12), "1");
 map.put(new Student("shu",13), "2");
 map.put(new Student("dashu",14), "3");
 // 取出数据
 for(Map.Entry<String,String> m : map.entrySet()){
  Student key = m.getKey();
  String value = m.getValue();
  System.out.println(key + " : " + value);
 }
 }
}
      
public class ComparatorByName implements Comparator<Student>{
 @Override
 public int compare(Student o1, Student o2){
  int temp = o1.getName().compareTo(o2.getName());
  return temp == 0 ? o1.getAge() - o2.getAge() : temp;
 }
}
      

04

实例:

public class CollectionsDemo {
   public static void main(String[] args) {
      Map m = new HashMap(); 
      m.put("da", "8");
      m.put("shu", "9");
      m.put("dashu", "10");
      m.put("dashucoding", "12");
      System.out.println(m);
   }
}
      

​Java Map​

​ 集合类

最常用的集合类就是​

​List​

​和​

​Map​

​,​

​List​

​的实现类包括​

​ArrayList​

​Vector​

​,可以变大小的列表,适合构建,存储,和操作任何类型对象元素的列表。

​Map​

​是比较通用的,​

​Map​

​集合类是用于存储元素对的,为键-值对,每个键映射到一个值,从理解上可以将​

​List​

​看作数值键的​

​Map​

​,但两者没有什么关系。

所有键值对 — ​

​entrySet()​

所有键 —

keySet()

值 —

values()

Iterator keyValues = map.entrySet().iterator();
Iterator keys = map.keySet().iterator();
Iterator values = map.values().iterator();
      

​entrySet()​

​:返回 ​

​Map​

​ 中所包含 映射 的 ​

​Set​

​ 视图。

​keySet()​

​Map​

​ 中所包含 键 的 ​

​Set​

​values()​

​Map​

​ 中所包含 值 的 ​

​Collection​

往后余生,唯独有你

90后帅气小伙,良好的开发习惯;独立思考的能力;主动并且善于沟通

简书博客: ​​https://www.jianshu.com/u/c785ece603d1​​

结语

  • 下面我将继续对 其他知识 深入讲解 ,有兴趣可以继续关注
  • 小礼物走一走 or 点赞

版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!