Map集合,将key对象映射到value对象
三个主要的子类:Hashtable,HashMap,TreeMap
Hashtable:底层是哈希表数据结构,不允许使用null值,线程同步
HashMap:底层是哈希表数据结构,允许使用null值,线程不同步
TreeMap:底层是二叉树数据结构,线程不同步,可以用于给Map集合中的键排序
使用keySet()方法遍历Map集合
调用Map对象的keySet()方法,得到Set对象,这里存储的是所有的键
import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class MapDemo { /** * @param args */ public static void main(String[] args) { Map<String,String> map=new HashMap<String,String>(); map.put("name", "taoshihan"); map.put("age", "100"); map.put("gender", "female"); Set<String> keySet=map.keySet(); for(String key:keySet){ System.out.println(map.get(key)); } //TreeMap可排序 Map<StudentTreeMap,String> treeMap=new TreeMap<StudentTreeMap,String>(); treeMap.put(new StudentTreeMap("taoshihan1", 40), "陶士涵"); treeMap.put(new StudentTreeMap("taoshihan2", 30), "陶士涵2"); treeMap.put(new StudentTreeMap("taoshihan3", 50), "陶士涵3"); Set<StudentTreeMap> treeMapSet=treeMap.keySet(); for(StudentTreeMap key:treeMapSet){ System.out.println(key.name+"====="+key.age); } } } class StudentTreeMap implements Comparable<StudentTreeMap>{ public int age; public String name; public StudentTreeMap(String name,int age) { this.name=name; this.age=age; } @Override public int compareTo(StudentTreeMap o) { if(o.age<this.age){ return 1; }else{ return -1; } } }
时间: 2024-11-04 20:11:48