Map、Debug】"/>
【Map、Debug】
【Map、Debug】
Map集合
Java.util.Map<K,V>
参数类型:
K - 此映射所维护的键的类型
V - 映射值的类型
将键映射到值的对象,一个映射不能包含重复的键,每个键最多只能映射到一个值。
Map集合的特点:
- Map集合是一个双列集合,一个元素包含两个值(一个Key,一个Value)
- Map集合中的元素,Key和Value的数据类型可以相同,也可以不同
- Map集合中的元素,Key不允许重复,Value是可以重复的
- Map集合中的元素,Key和Value一一对应
HashMap类
Java.util.HashMap<K,V> implements Map<K,V>
HashMap集合的特点:
- HashMap集合底层是哈希表:查询的速度特别快
- 在jdk1.8之前:数组 + 单向链表
- 在jdk1.8之后:数组 + 单向链表/红黑树(链表长度超过8):提高查询的速度
- HashMap集合是一个无序的集合,存储元素和取出元素的顺序有可能不一致
LinkedHashMap类
java.util.LinkedHashMap<K,V> extends HashMap<K,V>
LinkedHashMap集合的特点:
- LinkedHashMap集合底层是哈希表+链表(保证迭代的顺序)
- LinkedHashMap集合是一个有序的集合,存储元素和取出元素的顺序是一致的
Map接口中的常用方法
public V put(K key,V value)
:把指定的键与指定的值添加到Map集合中。
- 返回值:V
- 存储键值对的时候,Key不重复,返回值V是null
- 存储键值对的时候,Key重复,会使用新的Value替换旧的Value,返回值V是被替换的Value
public V remove(Object key)
:把指定的键所对应的键值对元素,在Map集合中删除,返回被删除的值。
- 返回值:V
- key存在,V返回被删除的值
- Key不存在,V返回null
public V get(Object key)
:根据指定的键,在Map集合中获取对应的值。
- 返回值:V
- key存在,V返回对应的value值
- key不存在,V返回null
public boolean containsKey(Object key)
:判断集合中是否包含指定的键。
- 包含返回true,不包含返回false
import java.util.HashMap;
import java.util.Map;public class Demo01Map {public static void main(String[] args) {//创建Map对象,使用多态Map<String, Integer> map1 = new HashMap<>();Map<String, String> map2 = new HashMap<>();put(map1);remove(map2);get(map2);containsKey(map2);}public static void put(Map<String, Integer> map) {Integer v1 = map.put("第一个数", 18);System.out.println("v1:" + v1);//v1:nullInteger v2 = map.put("第一个数", 19);System.out.println("v2:" + v2);//v2:18System.out.println(map);//{第一个数=19}map.put("第二个数", 28);map.put("第n个数", 28);System.out.println(map);//{第n个数=28, 第一个数=19, 第二个数=28}}public static void remove(Map<String, String> map) {map.put("赵丽颖", "女");map.put("杨颖", "女");map.put("林志颖", "男");System.out.println(map);//{赵丽颖=女, 杨颖=女, 林志颖=男}String removeName = map.remove("杨颖");System.out.println(removeName);//女}public static void get(Map<String, String> map) {String v3 = map.get("赵丽颖");System.out.println(v3);//女String v4 = map.get("杨颖");System.out.println(v4);//null}public static void containsKey(Map<String, String> map) {boolean b1 = map.containsKey("赵丽颖");boolean b2 = map.containsKey("杨颖");System.out.println("有赵丽颖:" + b1 + "有杨颖:" + b2);//有赵丽颖:true有杨颖:false}
}
Map集合遍历
键找值方式—keySet()
Map集合中有一个keySet方法:
public Set keySet(); 返回此映射中包含的键的Set视图
实现步骤:
- 使用Map集合中的方法keySet(),把Map集合所有的key取出来,存储到一个Set集合中;
- 遍历Set集合,获取Map集合中的每一个key;
- 通过Map集合中的方法get(key),通过key找到value。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;public class KeySetMethod {public static void main(String[] args) {//创建一个HashMap集合HashMap<String,Integer> map = new HashMap<>();map.put("James",23);map.put("Durant",35);map.put("Curry",30);map.put("Love",0);Set<String> set = map.keySet();//增强for循环for (String s : set) {Integer num = map.get(s);System.out.println(s+"="+num);}System.out.println("==========");//迭代器Iterator<String> it = set.iterator();while (it.hasNext()) {String key = it.next();Integer num = map.get(key);System.out.println(key + "=" + num);}}
}
Entry键值对对象
Map.Entry<K,V>:在Map接口中有一个内部接口Entry。
作用:当Map集合一创建,那么就会在Map集合中创建一个Entry对象,用来记录键与值(键值对对象,键与值的映射关系)。
public Set<Map.Entry<k,v>> entrySet(); 把Map集合内部的多个Entry对象取出来存到一个Set集合中
实现步骤:
- 遍历Set集合,获取Set集合的每一个Entry对象;
- 通过Entry对象的getKey()方法和getValue()方法分别获取相应的键和值,完成遍历。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;public class EntrySetMethod {public static void main(String[] args) {//创建一个HashMap集合HashMap<String, Integer> map = new HashMap<>();map.put("James", 23);map.put("Durant", 35);map.put("Curry", 30);map.put("Love", 0);Set<HashMap.Entry<String, Integer>> set = map.entrySet();//使用增强for循环遍历for (Map.Entry<String, Integer> obj : set) {String s = obj.getKey();Integer i = obj.getValue();System.out.println(s + "=" + i);}System.out.println("==========");//使用迭代器遍历Iterator<Map.Entry<String, Integer>> it = set.iterator();while (it.hasNext()) {Map.Entry<String, Integer> obj = it.next();String key = obj.getKey();Integer value = obj.getValue();System.out.println(key + "=" + value);}}
}
##HashMap集合存储自定义类型键值
Map集合保证key是唯一的:
- 作为key的元素,必须重写hashCode方法和equals方法,以保证key唯一。
import java.util.Objects;public class Player {private String name;private int number;public Player(){}public Player(String name,int number){this.name = name;this.number = number;}@Overridepublic String toString() {return "Player{" +"name='" + name + '\'' +", number=" + number +'}';}//重写equals方法和hashCode方法,保证元素同名元素重复@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Player player = (Player) o;return number == player.number &&Objects.equals(name, player.name);}@Overridepublic int hashCode() {return Objects.hash(name, number);}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getNumber() {return number;}public void setNumber(int number) {this.number = number;}
}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;public class HashMapSavePlayer {public static void main(String[] args) {show();/*Cavaliers:Player{name='James', number=23}Thunders:Player{name='Pual', number=3}Nets:Player{name='Durant', number=35}*/}public static void show(){//创建HashMap集合HashMap<Player,String> map = new HashMap<>();//往集合中添加元素map.put(new Player("James",23),"Lakers");map.put(new Player("Durant",35),"Nets");map.put(new Player("Pual",3),"Thunders");map.put(new Player("James",23),"Cavaliers");//使用entrySet方法和增强For循环遍历Map集合Set<Map.Entry<Player,String>> set = map.entrySet();for(Map.Entry<Player,String> player:set){Player playerInfo = player.getKey();String playerTeam = player.getValue();System.out.println(playerTeam+":"+playerInfo);}}
}
LinkedHashMap集合
Java.util.LinkedHashMap<K,V> extends HashMap<K,V>
Map接口的哈希表与链式列表的实现,具有可预知的迭代顺序。
底层原理:
- 哈希表+链表(记录元素的顺序)
import java.util.HashMap;
import java.util.LinkedHashMap;public class Demo01LinkedHashMap {public static void main(String[] args) {//HashMap不能保证存储与取出的顺序相同HashMap<String,String> map = new HashMap<>();map.put("b","b");map.put("d","d");map.put("c","c");map.put("a","a");System.out.println(map);//{a=a, b=b, c=c, d=d}//LinkedHashMap可以保证存储与取出的顺序相同LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();linkedMap.put("b", "b");linkedMap.put("d", "d");linkedMap.put("c", "c");linkedMap.put("a", "a");System.out.println(linkedMap);//{b=b, d=d, c=c, a=a}}
}
Hashtable集合
- 此类实现一个哈希表,该哈希表将键映射到相应的值。任何非null值都可以作为键或值。
特点:
- 底层也是一个哈希表;
- 是一个单线程的集合,线程安全,速度慢;
- 不允许存储null键和null值。
练习_计算一个字符串中每个字符出现次数
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;public class Exer {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("请输入字符,获得每个字母出现的次数:");String str = sc.next();findChar(str);}public static void findChar(String str) {HashMap<Character, Integer> map = new HashMap<>();char[] charArray = str.toCharArray();for (char c : charArray) {if (map.containsKey(c)) {Integer value = map.get(c);value++;map.put(c, value);} else {map.put(c, 1);}}Set<Map.Entry<Character, Integer>> entry = map.entrySet();for (Map.Entry<Character, Integer> characterIntegerEntry : entry) {Character key = characterIntegerEntry.getKey();Integer value = characterIntegerEntry.getValue();System.out.println(key + "出现的次数为:" + value);}}}
jdk9对集合添加的优化_of方法
jdk9的新特性:
- List接口,Set接口,Map接口:里面添加了静态的方法of,可以给集合一次性添加多个元素。
使用前提:
- 当集合中存储的元素的个数已经确定了,不再改变时可以使用of方法;
注意:
- of方法只是用与List接口、Set接口、Map接口,不使用于接口的实现类;
- of方法的返回值是一个不能改变的集合,集合不能再使用add或者put增加元素,会抛出异常;
- Set接口和Map接口在调用of方法的时候,不能有重复的元素,否则会抛出异常。
import java.util.List;
import java.util.Map;
import java.util.Set;public class Methodof {public static void main(String[] args) {List<String> list = List.of("a", "b", "c");Set<Integer> set = Set.of(1, 2, 5, 4, 3);Map<String, Integer> map = Map.of("d", 1, "c", 2);System.out.println(list);System.out.println(set);System.out.println(map);//不能使用add和put方法//list.add("2");//UnsupportedOperationException//map.put("f",3);//UnsupportedOperationException//Map集合和Set集合不能存储重复的元素//Set<Integer> set1 = Set.of(1, 1, 2, 3, 1);//IllegalArgumentException: duplicate element: 1}
}
Debug追踪
Debug调试程序:
- 可以让代码逐行运行,查看代码执行的过程,调试程序中出现bug。
使用方式:
- 可以在行号的右边,鼠标左键单击,添加断点(每个方法的第一行,哪里有bug添加到哪里)
- 右键,选择Debug执行程序
- 程序就会停留在添加的第一个断点处
执行程序:
按键 | 含义 |
---|---|
f8 | 逐行执行程序 |
f7 | 进入到方法中 |
shift + f8 | 跳出方法 |
f9 | 跳到下一个断点,如果没有下一个断点,那么久结束程序 |
ctrl + f2 | 退出Debug模式,停止程序 |
Consule | 切换到控制台 |
斗地主案例
案例分析
按照斗地主的规则,完成洗牌发牌的动作。
令狐冲:17张牌;
石破天:17张牌;
鸠摩智:17张牌;
底牌:3张牌。
具体规则:
- 组装54张扑克牌;
- 54张牌顺序打乱;
- 三个玩家参与游戏,三人交替摸牌,每人17牌,最后三张留底牌;
- 查看三个各自手中的牌(按照牌的大小顺序)、底牌。
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;public class Doudizhu {public static void main(String[] args) {HashMap<Integer,String> poker = new HashMap<>();ArrayList<Integer> pokerindex = new ArrayList<>();List<String> colors = List.of("♠", "♥", "♣", "♦");List<String> numbers = List.of("2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3");//生成牌int index = 0 ;poker.put(index,"大王");pokerindex.add(index);index++;poker.put(index,"小王");pokerindex.add(index);index++;for (String color : colors) {for (String number : numbers) {poker.put(index,color+number);pokerindex.add(index);index++;}}
// System.out.println(pokerindex);
// System.out.println(poker);Collections.shuffle(pokerindex);
// System.out.println(pokerindex);ArrayList<Integer> player01 = new ArrayList<>();ArrayList<Integer> player02 = new ArrayList<>();ArrayList<Integer> player03 = new ArrayList<>();ArrayList<Integer> dipai = new ArrayList<>();for (int i = 0; i < pokerindex.size(); i++) {if(i>=51){dipai.add(pokerindex.get(i));}if(i % 3 == 0){player01.add(pokerindex.get(i));}if (i % 3 == 1){player02.add(pokerindex.get(i));}if (i % 3 == 2){player03.add(pokerindex.get(i));}}Collections.sort(dipai);Collections.sort(player01);Collections.sort(player02);Collections.sort(player03);fapai("李元芳",poker,player01);fapai("张无忌",poker,player02);fapai("柳岩",poker,player03);fapai("底牌",poker,dipai);}public static void fapai(String name,HashMap<Integer,String> poker,ArrayList<Integer> pokerindex){System.out.print(name+":");for (Integer integer : pokerindex) {String s = poker.get(integer);System.out.print(s+" ");}System.out.println("");}
}
更多推荐
【Map、Debug】
发布评论