Map集合的常用方法
引用格式:
import java.util.HashMap;
import java.util.Map;
public class Test3 {
public static void main(String[] args) {
//Map
Map<String,Integer> scores = new HashMap<String,Integer>();
}
<String,Integer>,其中String用于限定key的数据类型,Integer显示value的数据类型,泛型不能使基本数据类型。
.put(key, value)方法
作用:向集合中添加数据;
格式:对象名…put(key, value);(key为限定的数据类型,value为数据内容)
代码:
scores.put("Tom", 100);//添加数据
scores.put("Jim", 60);
scores.put("Jim", 60);
.get(key)方法:
作用:获取对应位置index的数据,用法与数组相似,从零开始计数。
格式:变量名 = 对象名.get(key);且Map集合key不允许重复,重复的话以最后一个为主
代码:
int score = scores.get("Jim");//获取Jim成绩
System.out.println(score);
结果为:
60
.size()方法:
作用:统计集合中有多少元素(元素可以重复储存)
格式:对象名.size();
代码:
int size = scores.size();//个数
System.out.println(size);
结果为:
2
.isEmpty()方法:
作用:判断集合中是否有元素,若有则返回true;若没有,则返回false
格式:对象名.isEmpty();
代码:
boolean flag = scores.isEmpty();//判断是否为空
System.out.println(flag);//false
.clear()方法:
作用:清空集合中的所有元素
格式:对象名.clear();
代码:
scores.clear();//清空
flag = scores.isEmpty();
System.out.println(flag);//true
.get(key)方法
作用:获取指定位置key的value数据;
格式:.get(key);
代码:
score = scores.get("Jim");
System.out.println(score);
.replace(key, value)方法
作用:在指定元素key的数据替换为新的value
格式:对象名.replace(key, value);
代码:
scores.replace("Jim", 0);//将Jim的100替换Jim 0
score = scores.get("Jim");
System.out.println(score);
整体代码:
import java.util.HashMap;
import java.util.Map;
public class Test3 {
public static void main(String[] args) {
//Map
Map<String,Integer> scores = new HashMap<String,Integer>();
scores.put("Tom", 100);//添加数据
scores.put("Jim", 60);//Map集合key不允许重复,重复的话以最后一个为主
int score = scores.get("Jim");//获取Jim成绩
System.out.println(score);
int size = scores.size();//个数
System.out.println(size);
scores.clear();//清空
size = scores.size();
System.out.println(size);
boolean flag = scores.isEmpty();//判断是否为空
System.out.println(flag);
scores.put("Jim", 100);
scores.replace("Jim", 0);//替换
score = scores.get("Jim");
System.out.println(score);
}
}