从头认识java-9.10 Map

来源:互联网 发布:vasp软件价格 编辑:程序博客网 时间:2024/06/05 08:53

这一章节我们来讨论一下Map。

Map就是“键值”关联数组。

1.演示

package com.ray.ch09;import java.util.HashMap;import java.util.Random;public class Test {public static void main(String[] args) {HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();Random random = new Random();for (int i = 0; i < 10; i++) {int key = random.nextInt(50);if (map.get(key) == null) {map.put(key, 1);} else {int value = map.get(key);map.put(key, value + 1);}}System.out.println(map.toString());}}


输出:

{19=1, 38=1, 36=1, 37=1, 42=1, 10=1, 40=1, 41=1, 11=1, 45=1}

注意:由于我们上面的代码使用hashmap,因此它记录的结果是无序的,当我们下一次运行代码的时候,它们的顺序将会不一样。

 

2.常用方法containKeys和containValue

package com.ray.ch09;import java.util.HashMap;import java.util.Random;public class Test {public static void main(String[] args) {HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();Random random = new Random();for (int i = 0; i < 10; i++) {int key = random.nextInt(50);if (map.get(key) == null) {map.put(key, 1);} else {int value = map.get(key);map.put(key, value + 1);}}System.out.println(map.toString());System.out.println(map.containsKey(3));System.out.println(map.containsValue(5));}}


输出:

{32=1, 18=1, 38=1, 5=1, 23=1, 6=1, 42=1, 43=1, 29=1, 15=1}
false
false

一般我们会使用上面的方法来测试map里面是否有我们想要的对象。

 

3.把数据发展到多维。

package com.ray.ch09;import java.util.ArrayList;import java.util.HashMap;public class Test {public static void main(String[] args) {HashMap<Person, ArrayList<Pet>> map = new HashMap<Person, ArrayList<Pet>>();Person person = new Person();ArrayList<Pet> pets = new ArrayList<Pet>();for (int i = 0; i < 10; i++) {pets.add(new Pet());}map.put(person, pets);}}class Person {}class Pet {}


上面的代码其实我们已经把数据机构变成了多维的形式。

 

总结:这一章节主要讲述了HashMap的使用。

 

这一章节就到这里,谢谢。

-----------------------------------

目录

 

0 1
原创粉丝点击