Map接口_HashMap常用的方法

package Map;

import java.util.HashMap;
import java.util.Map;

/**
* 测试HashMap的使用
*/
public class TestMap {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<>();
//增加
map.put(1,"one");
map.put(2,"two");
map.put(3,"three");
//获取
System.out.println(map.get(1));
System.out.println(map.size());
System.out.println(map.isEmpty());
System.out.println(map.containsKey(1));
System.out.println(map.containsValue("four"));

Map<Integer,String> m1=new HashMap<>();
m1.put(4,"four");
map.putAll(m1);
System.out.println(map);
//map中键不能重复,如果重复(是否重复根据equals方法),新的值会覆盖旧的值
map.put(3,"five");
System.out.println(map);
}
}

二、泛型时对象
package Map;

import java.util.HashMap;
import java.util.Map;

public class TestMap2 {
public static void main(String[] args) {
Map<Integer,Student> m1=new HashMap<>();
m1.put(1001,new Student(10001,"小明",3000));
Student s1=m1.get(1001);
System.out.println(s1.getName());
}
}




class Student{
int id;
String name;
int salary;

public int getId() {
return id;
}

public int getSalary() {
return salary;
}

public String getName() {
return name;
}
public Student(int id,String name,int salary){
this.id=id;
this.name=name;
this.salary=salary;
}

@Override
public String toString() {
return "id"+id+"名字"+name+"薪水"+salary;
}
}


posted on 2019-06-12 21:39  zz测试笔记  阅读(462)  评论(0编辑  收藏  举报