您的位置:首页 > 运维架构 > 网站架构

java集合架构 图HashMap

2018-02-12 15:11 253 查看
         Map接口建立元素和键的映射关系。键就像下标,在List中,下标就是整数;而在Map中,键可以是任意类型的对象。图中不能有重复的键,每个键对应一个值。

对于定位一个值,插入一个映射或删除一个映射,HashMap类的效率是很高的。

LinkedHashMap类是在JDK1.4中引入的,它用链表实现的扩展HashMap类,它支持图中元素的排序。在HashMap 类中元素是没有顺序的,但是在LinkedHashMap中,元素既可以按照他们插入图的顺序排列(插入顺序),也可以按照他们最后一次访问时间的顺序,从早到晚(访问顺序)排序。无参构造是按插入顺序来创建对象的;要按照访问顺序来创建对象应使用构造方法:LinkedHashMap(initialCapacity,loadFactor,true)。

TreeMap类实现SortedMap接口,很适合按照排好的顺序遍历图。键可以使用Comparable接口或者Comprator接口来排序。

package 集合架构;
import java.util.*;

//图
public class TestMap {
public static void main(String[] args){
//Create a HashMap
Map<String,Integer> hashMap = new HashMap<String,Integer>();
hashMap.put("Smith",30);
hashMap.put("Anderson",31);
hashMap.put("Lewis",29);
hashMap.put("Cook",29);

System.out.println("Display entries in HashMap");
System.out.println(hashMap); //hashMap中元素的存储数据是随机的

//Create a TreeMap from the previous HashMap
Map<String,Integer> treeMap = new TreeMap<String,Integer>(hashMap);
System.out.println("\nDisplay entries in ascending order of key");
System.out.println(treeMap); //treeMap中的元素是按键的升序存储的

//Create a LinkedHashMap
Map<String,Integer> linkedHashMap = new LinkedHashMap<String,Integer>(16,0.75f,true);
linkedHashMap.put("Smith",30);
linkedHashMap.put("Anderson",31);
linkedHashMap.put("Lewis",29);
linkedHashMap.put("Cook",29);

//Display the age for "Lewis"
System.out.println("The age for"+"Lewis is "+linkedHashMap.get("Lewis").intValue());

System.out.println("\nDisplay entries in LinkedHashMap");
System.out.println(linkedHashMap); //linkedHashMap中的元素是按元素最后一次访问的时间来存储的,从早排到晚

}
}

如果更新图时不需要保持图中元素的顺序,选用HashMap,因为它在HashMap中插入和删除映射花费的时间最少。如果需要保持图中元素插入顺序或访问顺序,则选择LinkedHashMap。如果需要按键排序,则将该图转换为树形图。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java hashmap