Map is a function to save data through key-values.Correspondingly,the 'key' and the 'value' are the key words.
We usually create a Map object with HashMap,and there will be corresponding ways to save data
Map<String,Person> map = new HashMap<>();
map.put("jack", new Person("jack", 90, 15));
map.put("merry", new Person("merry", 90, 18));
And then,there also exists many methods to modify these stored data.
Map
Interface Map(映射)
HashMap
class Person implements Comparable<Person> {
protected float score;
protected String name;
protected int age;
public Person(String name,float score,int age){
this.name = name;
this.score = score;
this.age = age;
}
@Override
public String toString() {
return "name:"+name+ " "+"score:" + score + " "+"age:"+age;
}
public class MyClass {
public static void main(String[] args) {
/**
* Map - Interface Map(映射)
* -|HashMap Manage the key-value pairs
* -|ConcurrentMap About the safety of threads
* -|LinkedHashMap
* Dictionary key - key-value(键值对0
* key: 键
* value: 值
*
* [ key: value, key: value];
*/
// Map<String, Person> map = new HashMap<>();
Map<String,Person> map = new HashMap<>();
// Add a key-value
map.put("jack", new Person("jack", 90, 15));
map.put("merry", new Person("merry", 90, 18));
// Get the count of key-value
System.out.println(map.size());
// Whether containing a 'ker'
System.out.println(map.containsKey(("jack22")));
//Whether containing certain 'value'
System.out.println(map.containsValue((person)));
// Get corresponding value of certain key
Person p = map.get("jack");
System.out.println("jack"+ p);
// Delete certain key-value
//map.remove("jack");
System.out.println(map);
// Take place one certain key-value
map.replace("jack",new Person("张三",99,19));
System.out.println(map);
//map.clear();
//the Traverse of map
Set<Map.Entry<String, Person>> entries = map.entrySet();
for(Map.Entry<String,Person> entry : entries){
System.out.println("key:"+ entry.getKey() + " value:"+ entry.getValue());
2
false
false
jackname:jack score:90.0 age:15
{jack=name:jack score:90.0 age:15, merry=name:merry score:90.0 age:18}
{jack=name:张三 score:99.0 age:19, merry=name:merry score:90.0 age:18}
key:jack value:name:张三 score:99.0 age:19
key:merry value:name:merry score:90.0 age:18
}
}
Here is the example
map是以键值百对来存储数据的,例如:
Map map = new HashMap();
map.put("移动","10086");
String c = map.get("移动");
结果c="10086”;
简单来说,map就像我们手机的电话本,用map.put("移动","10086"),就是在电话本保存度了移动的电话,然后当你想拿移专动的电话时候就用String c = map.get("移动");就可以拿到电话号码了。