java - 泛型:java.lang.String 不能应用于 Student

标签 java generics

我在类里面,我的教授说她的代码可以工作,没有任何问题,而且一定是我。我查看了她的代码并像她所说的那样逐字复制,但我仍然收到错误:

Pair.java:28: set(java.lang.String,java.lang.Double) in Pair cannot be applied to (Student,java.lang.Double)

我加粗的部分是我收到错误的部分。设置方法是否错误?因为有错误的行会返回到设置方法

这是她的代码:

学生.java

import java.io.*;

public class Student implements Person {
  String id;
  String name;
  int age;

  //constructor
  public Student(String i, String n, int a) {
    id = i;
    name = n;
    age = a;
  }

  public String getID() {
    return id;
  }

  public String getName() {
    return name; //from Person interface
  } 

  public int getAge() {
    return age; //from Person interface
  }

  public void setid(String i) {
    this.id = i;
  }

  public void setName(String n) {
    this.name = n;

  }

  public void setAge(int a) {
   this.age = a;
  }

  public boolean equalTo(Person other) {
    Student otherStudent = (Student) other;
    //cast Person to Student
    return (id.equals(otherStudent.getID()));
  }

  public String toString() {
    return "Student(ID: " + id + 
      ",Name: " + name +
      ", Age: " + age +")";
  }
}

Person.java

import java.io.*;

public interface Person {
  //is this the same person?
  public boolean equalTo (Person other);
  //get this persons name
  public String getName();
  //get this persons age
  public int getAge();
}

配对.java

import java.io.*;

public class Pair<K, V> {

  K key;
  V value;
  public void set (K k, V v) {
    key = k;
    value = v;
  }

  public K getKey() {return key;}
  public V getValue() {return value;}
  public String toString() {
    return "[" + getKey() + "," + getValue() + "]";
  }

  public static void main (String [] args) {
    Pair<String,Integer> pair1 = 
      new Pair<String,Integer>();
    pair1.set(new String("height"),new
                Integer(36));
    System.out.println(pair1);
    Pair<String,Double> pair2 = 
      new Pair<String,Double>();

    //class Student defined earlier
    **pair2.set(new Student("s0111","Ann",19),**
              new Double(8.5));
    System.out.println(pair2);
  }
}

最佳答案

对于实例化:

Pair<String,Double> pair2 = new Pair<String,Double>();

您的set()方法签名相当于:set(String, Double)。并且您在下面的调用中向其传递 Student 引用,这是行不通的,因为 Student 不是 String

pair2.set(new Student("s0111","Ann",19), new Double(8.5));

要避免此问题,请将 pair2 的声明更改为:

Pair<Student,Double> pair2 = new Pair<Student,Double>();

关于java - 泛型:java.lang.String 不能应用于 Student,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19037336/

相关文章:

java - 在 Java 中读写同一个文件

java - 我应该在我的应用程序上使用什么 OAuth 2 工作流程

java - 从 ANTLR 中的语法规则调用方法?

java - Mac 上的 SWT 和 Swing

generics - 如何在 Rust 中正确设置通用集合类型

typescript - 返回具有相同属性名称的类型

java - Java 5.0 中包含泛型值得吗?

java - 仅在使用 SurfaceView 的 Samsung GT-I8260 中渲染视频时出现问题。异常 : Prepare failed.:状态=0x1

c# - 通用 Linq 查询 NotSupportedException : Could not parse expression

c# - 获取对动态对象中方法的泛型调用