与Set不同之处是,Map接口的对象将键映射至值,因此,在加载内容的时候,就会有键和值两个。读取的时候,直接按照键去读出值。
以下是HashMap的用法:
import java.util.*;
public class HashMapdemo{
public static void main(String[] args){
HashMap<String,String> hashmap=new HashMap<String,String>();
hashmap.put("lele","laolong");
hashmap.put("pipi","laonan");
System.out.print(hashmap.get("lele"));
System.out.print(" nihao ");
System.out.print(hashmap.get("pipi"));
}
}
TreeMap也是相同的用法,只不过是在排序的时候,默认是根据字典排序的。
本文介绍了Java中HashMap的基本用法,包括键值对的添加和读取,并通过示例代码进行说明。此外,还对比了TreeMap的使用,强调其默认按照字典顺序排序的特点。
548

被折叠的 条评论
为什么被折叠?



