引用格式:
import java.util.HashMap;
import java.util.Map;
public class Test{
public static void main(String[] args) {
Map<String,Integer> scores = new HashMap<String,Integer>();
String用于限定key的数据类型,Integer显示value的数据类型,泛型不能使基本数据类型
常用方法
put(key, value) : 向集合中添加数据;
get(key) : 从零算起,获取key上的元素;
size() : 统计集合内元素个数;
isEmpty() : 判断集合是否为空;
clear() : 清空集合内元素;
replace(key, value) :在指定元素key的数据替换为新的value;
代码示例
package test1;
import java.util.Map;
import java.util.HashMap;
public class Test {
public static void main(String[] args){
Map<String,Integer> scores = new HashMap<String,Integer>();
scores.put("Jim", 100);
scores.put("Jim", 110);//Map集合key不允许重复,重复的话以最后一个为主
int score = scores.get("Jim");//获取key上的值110
System.out.println(score);
int size = scores.size();
System.out.println(size);//输出集合长度
scores.clear();//清空集合
boolean flag = scores.isEmpty();
System.out.println(flag);//true
scores.put("Jim", 100);
scores.replace("Jim", 60);//将Jim位的100替换为60
score = scores.get("Jim");
System.out.println(score);
}