我在课堂上,我的教授说她的代码有效,并且没有任何问题,而且一定是我。我已经查看了她的代码,并按照她的说法逐字复制,但我仍然收到错误:
Pair.java:28:set中的set(java.lang.String,java.lang.Double)无法应用于(Student,java.lang.Double)
我加粗的部分是我收到错误的部分。设定方法不正确吗?因为带有错误的行返回到set方法
这是她的代码:
Student.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();
}
Pair.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);
}
}
答案 0 :(得分:3)
对于实例化:
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>();
答案 1 :(得分:2)
错误非常自我解释。 pair2定义为Pair<String, Double>
。您正在尝试设置Student, Double
。那不行。
答案 2 :(得分:2)
Pair<String,Double> pair2 = new Pair<String,Double>();
应该是:
Pair<Student,Double> pair2 = new Pair<Student,Double>();
答案 3 :(得分:1)
pair2
中的被定义为Pair<String,Double>
类型,即pair2
set()
方法期望String
,Double
作为参数,但是您正在通过Student
,Double
所以
Pair<String,Double> pair2 = new Pair<String,Double>();
应该是
Pair<Student,Double> pair2 = new Pair<Student,Double>();