2013-09-26 71 views
0

我在課堂上,我的教授說她的代碼有效,它沒有任何問題,它一定是我。我已經看了看她的代碼,並將它複製一個字一個字一樣,她說不過我仍然收到錯誤:泛型:java.lang.String不能應用於學生

Pair.java:28: set(java.lang.String,java.lang.Double) in Pair cannot be applied to (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); 
    } 
} 
+1

應'對<學生,雙> pair2 =一雙新<學生,雙>();'。 – Marcelo

回答

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>(); 
2

這個錯誤很自我解釋。 pair2被定義爲Pair<String, Double>。您正試圖設置一個Student, Double。這是行不通的。

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

應該是:

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

從您的代碼pair2被定義爲Pair<String,Double>型,即方法pair2set()期待String,Double作爲參數,但您通過Student,Double
所以

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

應該是

Pair<Student,Double> pair2 = new Pair<Student,Double>(); 
相關問題