Sophia Ali Sophia Ali - 2 years ago 120
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: 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:


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

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) { = i;

public void setName(String n) { = 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 +")";


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


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
Pair<String,Double> pair2 =
new Pair<String,Double>();

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

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