Swadhikar C Swadhikar C - 1 year ago 69
Java Question

Error extending LinkedHashMap

I am trying to extend

LinkedHashMap
from my Students class. By this I want to bring in all functionalities of a Map like
Map.put(value)
,
Map.get(key)
. I just create the object inside PSVM and not making static references but still I get the below error. Can someone point me as to what mistake I am committting here? Also is there a better approach to achieve the task? Thanks in advance!

import java.util.LinkedHashMap;

public class Students<Integer,String> extends LinkedHashMap<Integer,String> {

public static void main(String args[]) { // line 5
Students<Integer,String> students = new Students<>(); // line 6
students.put(1, "s1");
students.put(2, "s2");
students.put(3, "s3");

System.out.println(students.get(1));
}

}


Error Message:

>> javac Students.java
Students.java:5: error: non-static type variable String cannot be referenced from a static context
public static void main(String args[]) {
^
Students.java:6: error: non-static type variable Integer cannot be referenced from a static context
Students<Integer,String> students = new Students<>();
^
Students.java:6: error: non-static type variable String cannot be referenced from a static context
Students<Integer,String> students = new Students<>();
^
Students.java:6: error: unexpected type
Students<Integer,String> students = new Students<>();
^
required: class
found: <Integer,String>Students<Integer,String>
where Integer,String are type-variables:
Integer extends Object declared in class Students
String extends Object declared in class Students
4 errors

Answer Source

By doing

class Student<Integer, String>

You have defined your own generic types Integer and String. These are associated with the instance of the class Student however you are also attempting to use these new generic types in your main() method which is a static rather than an instance class and this is not allowed. What you intended to use as java.lang.String

The simple solution is

  • don't define you own generic types, you don't need to.
  • don't extend LinkedHashMap but rather use composition as this limits the methods you expose.

e.g.

public class Students {
    private final Map<Integer, String> map = new LinkedHashMap();

    public void put(int num, String str) { map.put(num, str); }

    public String get(int num) { return map.get(num); }

    public static void main(String args[]) { 
        Students students = new Students(); 
        students.put(1, "s1");
        students.put(2, "s2");
        students.put(3, "s3");

        System.out.println(students.get(1));
    }
}