Sophia Ali Sophia Ali - 1 year ago 99
Java Question

Generics: java.lang.String cannot be applied to Student

I am in class and my professor is saying her code works and there is nothing wrong with it and that it must be me. I have looked over her code and copied it word for word like she stated however I am still receiving the error:


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


The part I bolded is the part I receive an error on. Are the set methods incorrect? Because the line with the error goes back to the set methods

This is her code:

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);
}
}

Answer Source

For the instantiation:

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

your set() method signature is equivalent to: set(String, Double). And you are passing it a Student reference in the below invocation, which wouldn't work, as Student is not a String.

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

To avoid the issue, change the declaration of pair2 to:

Pair<Student,Double> pair2 = new Pair<Student,Double>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download