Map集合常用实现类

1、HashMap:无序

package com.xn.ffri;

import java.util.HashMap;

public class Fri06 {
	public static void main(String[] args) {
		//HashMap
		//KV键值对集合,key唯一,value允许重复
		HashMap cityMap=new HashMap();
		//put()方法:添加键值对
		//如果key不存在,键返回null
		System.out.println(cityMap.put("X西安",11111));
		System.out.println(cityMap.put("C长沙",22222));
		System.out.println(cityMap.put("X厦门",33333));
		System.out.println(cityMap.put("W武汉",44444));
		//如果key存在,则保存新value,返回旧value
		System.out.println(cityMap.put("X西安",11112));
		//
		int value1=cityMap.get("C长沙");
		System.out.println("C长沙 ==>"+value1);
		
		Integer value3=cityMap.get("G贵阳");
		System.out.println("G贵阳 ==>"+value3);
		
		int value2=cityMap.get("G贵阳");
		System.out.println("G贵阳 ==>"+value2);
	}
}

2、LinkedHashMap:有序

package com.xn.ffri;

import java.util.HashMap;
import java.util.LinkedHashMap;

public class Fri09 {
	public static void main(String[] args) {
		String str="hfdshsvhsuvhsdoarfregerjcxxoivpohytj";
		//无序
//		HashMap map=new HashMap();
		//有序
		LinkedHashMap map= new LinkedHashMap();
		for(int i=0;i

3、TreeMap:按照key自动排序

package com.xn.ffri;

import java.util.Comparator;
import java.util.TreeMap;
import java.util.Map.Entry;

public class Fri10 {
	public static void main(String[] args) {
		//TreeMap:按照key自动排序,通过key进行比较后排序
		//HashMapmap new HashMap();
		//TreeMap:按照key自动排序,通过key进行比较后排序

		TreeMap map=new TreeMap( new Comparator() {

			@Override
			public int compare(String o1, String o2) {
				int n1=Integer.parseInt(o1.substring(2));
				int n2=Integer.parseInt(o2.substring(2));
				return n1-n2;
			}
		});
		map.put("FC104", "A1");
		map.put("FC1612", "A2");
		map.put("FC1245", "A3");
		map.put("FC187", "A4");
		map.put("FC14599", "A5");
		map.put("FC167", "A6");
		map.put("FC1469", "A7");
		map.put("FC1989", "A8");
		map.put("FC1528", "A9");
		
		for(Entry entry : map.entrySet()) {
			System.out.println(entry);
		}
	}
}

4、Hashtable:无序;线程安全,性能低;不允许使用null做key;不允许使用null做value

你可能感兴趣的:(java,开发语言)