使用映射

mac2026-04-20  9

映射是存储键和值之间关联关系的对象。给定一个键,就可以找到对应的值。键和值都是对象。键必须唯一,但是值可以重复。

关键点:没有实现Iterator接口。意味着不能使用for-each风格的for循环遍历映射。此外,不能为映射获取迭代器。但是,可以获取映射的集合视图,集合视图允许使用for循环和迭代器。

映射围绕两个方法get()和put()。为了将值放入映射中,使用put()方法,指定键和值。为了获取值,调用get()方法,传递键作为参数,值会被返回。尽管映射是集合框架的一部分,但是映射不是集合,因为没有实现Collection接口。但是可以获得映射的集合视图。为此可以使用entrySet()方法。该方法返回一个包含映射中元素的Set对象。为了获取键的集合视图,使用KeySet()方法;为了得到值的集合视图,使用values()方法。对于这三个集合视图,集合都是基于映射的,修改其中一个集合会影响其他集合。集合视图是将映射集成到更大集合框架的手段。

使用hashMap:

 

package Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @author 犀角 * @date 2019/11/2 10:30 * @description 使用HashMap将名字映射到账户金额,注意获取和使用组视图: */ public class HashMapDemo { public static void main(String[] args) { HashMap<String,Double> hashMap = new HashMap<String, Double>(); hashMap.put("U",new Double(97869)); hashMap.put("YUU",new Double(8987.868)); hashMap.put("UGUFG",new Double(8675.756)); hashMap.put("uyeu",new Double(755.9787)); //get a set of entries Set<Map.Entry<String,Double>> set = hashMap.entrySet(); //display the set for (Map.Entry<String,Double>me:set){ System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); //Desosit 1000 into U's account double balance = hashMap.get("U"); hashMap.put("U",balance + 1000); System.out.println("U's new balance:"+balance); } }

使用TreeMap类:

package Collection; import java.util.*; class TreeMapDemo { public static void main(String[] args) { TreeMap<String, Double> tm = new TreeMap<String, Double>(); tm.put("asdf",new Double(3434.34)); tm.put("asde",new Double(245.36)); tm.put("yuy",new Double(76.87)); tm.put("ywyty",new Double(097.87)); Set<Map.Entry<String,Double>> set=tm.entrySet(); for(Map.Entry<String,Double> me:set){ System.out.print(me.getKey()+" : "); System.out.println(me.getValue()); } System.out.println(); double balance=tm.get("asdf"); tm.put("asdf",balance+1000); System.out.println("asdf's new balance:"+tm.get("asdf")); } }

 

最新回复(0)