集合框架-实现类(HashMap)

本文深入解析了Java中HashMap的使用方法,包括长度、获取、增加、删除、修改和比较等核心操作,通过具体代码示例展示了如何操作键值对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、基本含义

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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值