【问题标题】:why can't i do the hashmap.put()为什么我不能做 hashmap.put()
【发布时间】:2020-08-05 18:05:19
【问题描述】:

每当我尝试运行时,我的错误就是“hmap.put(id, b0);”我做得对吗?我正在尝试进行用户输入并将其插入哈希图中。 它说: 没有找到适合 put(Integer,Student) 的方法 方法 Map.put(Integer,String) 不适用 (参数不匹配;学生不能转换为字符串) 方法 AbstractMap.put(Integer,String) 不适用 (参数不匹配;学生不能转换为字符串) 方法 HashMap.put(Integer,String) 不适用

(参数不匹配;Student 无法转换为字符串)

package javaapplication30;
import java.util.*;
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;

class Student {
  int id;
  String sn, cor;

  public Student(int id, String sn, String cor) {
    this.id = id;
    this.sn = sn;
    this.cor = cor;

  }
}

public class JavaApplication30 {
  public static void main(String[] args) {
    HashMap < Integer, String > hmap = new HashMap < Integer, String > ();
    Scanner sc = new Scanner(System.in);

    for (int i = 0; i < 2; i++) {
      System.out.print("id: ");
      Integer id = sc.nextInt();
      System.out.print("name: ");
      String sn = sc.next();
      System.out.print("course: ");
      String cor = sc.next();

      Student b0 = new Student(id, sn, cor);

      hmap.put(id, b0);

    }

    for (Map.Entry m: hmap.entrySet()) {
      System.out.println(m.getKey() + " " + m.getValue());
    }
  }
}

【问题讨论】:

  • b0 的类型为Student,但应为String 或使用HashMap &lt; Integer, Student &gt;
  • @Pavneet_Singh 非常感谢!我忘记了那一部分,现在我可以修复它了!非常感谢!

标签: java hash hashmap


【解决方案1】:

您已将地图声明为HashMap&lt;Integer, String&gt;。也就是说,键类型为Integer,值类型为String

但是你这样做:

  Student b0 = new Student(id, sn, cor);
  hmap.put(id, b0);

这是尝试添加值为Student 的映射条目。

Student 不是String 的子类,因此这是不合法的。


这是错误消息的内容,以及如何解释它:

no suitable method found for put(Integer,Student) 

这对应于这个调用put(id, b0)。观察id 被声明为Integerb0Student

method Map.put(Integer,String) is not applicable 

编译器在Map接口中发现了一个put方法,其签名为put(Integer,String)。它有正确的 name 和正确的 number 个参数。但是……

(argument mismatch; Student cannot be converted to String)

编译器试图找到一种合法的方式来使用put 方法。第一个参数是兼容的,但没有将Student(参数是什么)转换为String(该方法需要)的转换。

解决方法是更改​​hmap的声明:

HashMap<Integer, Student> hmap = new HashMap<>();

&lt;&gt; 告诉编译器从上下文中推断(即计算出)泛型类型参数。)

【讨论】:

    【解决方案2】:

    您将 Hasmap 声明为: new HashMap&lt;Integer, String&gt;();

    那么你的 HashMap 期望 Integer 作为键,String 作为值。 您的对象 b0 不是字符串,而是学生对象。

    那你应该把你的HashMap改成new HashMap&lt;Integer, Student&gt;();(或者你可以在b0上调用toString()函数,这取决于你想做什么)

    【讨论】:

      猜你喜欢
      • 2018-10-24
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 2011-05-04
      相关资源
      最近更新 更多