集合框架-实现类(HashMap)

一、基本含义

Map接口 →HashMap实现类。
名称:哈希表。

二、长度——size()

public class MapTest {
  public Map<String,Student> clazzStudents;
  private Scanner scanner;
  public MapTest() {
    this.clazzStudents = new HashMap<String,Student>();
    this.scanner = new Scanner();
  }
  public static void main(String[] args){
    System.out.println(clazzStudents.size());
  }
}

三、获取

3.1 知key

key具有唯一性,所以返回一个对象。

public Student testKeySet(String key){
  Student stu = null;
  Set<String> keySet = clazzStudents.keySet();
  Iterator<String> it = keySet.iterator();
  while(it.hasNext()){
    if(it.next().equals.(key)){
      stu = clazzStudents.get(key);
      System.out.println("学生【ID=" + stu.getId() + ",姓名=" + stu.getName() + "】");
      break;
    }
  }
	return stu;
}

3.2 知value

value具有可重复性,所以返回多个对象。

public Set<Student> testEntrySet(String name) {
  Set<Student> studentSet = new HashSet<Student>();
  Set<Entry<String,Student>> entrySet  = clazzStudents.entrySet();
  for (Entry<String,Student> entry : entrySet) {
     if(entry.getValue().getName().equals(name)){
       studentSet.add(entry.getValue());
     }
  }
   return studentSet;
}

3.3 复制——clone()


四、增加

4.1 元素为对象时——put()

put(K key, V value)

clazzStudents.put("2",new Student("2","张三"));

4.2 元素为对象表时——putAll()

putAll(Map<? extends K,? extends V> m)

Map<String,Student> mapStudent = new HashMap<String,Student>();
mapStudent.put("1",new Student("1","张三"));
mapStudent.put("3",new Student("3","李四"));
mapStudent.put("2",new Student("2","王五"));
clazzStudents.putAll(mapStudent);

五、删除

5.1 知key——remove(Object key)

clazzStudents.remove(key);

5.2 知value——remove(Object key, Object value)

不常用。需要重写Student类中的equals()方法。

clazzStudents.remove("1",new Student("1","张三")); 

5.3 清空——clear()

clazzStudents.clear();

六、修改

6.1 put(K key, V value)

clazzStudents.put("1", new Student("1", "张四"));

6.2 replace(K key, V value)

clazzStudents.replace("1", new Course("1", "张四"));

6.3 replace(K key, V oldValue, V newValue)

不常用。

clazzStudents.replace("1",clazzStudents.get("1") ,new Course("1", "张四"));

七、比较

7.1 是否包含

7.1.1 containsKey(Object key)

clazzStudents.containsKey(id); 

7.1.2 containsValue(Object value)

不常用。需要重写Student类中equals()方法

clazzStudents.containsValue(new Student("1","张三"));

7.2 是否为空——isEmpty()

clazzStudents.isEmpty();

猜你喜欢

转载自blog.csdn.net/lizengbao/article/details/86695775