我正在尝试从我的学生班级扩展LinkedHashMap。我想借此引入Map的所有功能,例如Map.put(value)Map.get(key)。我只是在PSVM内创建对象,而不进行静态引用,但仍然收到以下错误。有人可以指出我在这里犯的错误吗?还有没有更好的方法来完成任务?提前致谢!

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

}


错误信息:

>> 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

最佳答案

通过做

class Student<Integer, String>


您已经定义了自己的通用类型IntegerString。它们与类Student的实例相关联,但是您还尝试在main()方法中使用这些新的泛型类型,它是静态的,而不是实例类,因此是不允许的。您打算用作java.lang.String的内容

简单的解决方案是


不需要定义自己的泛型类型,也不需要。
不要扩展LinkedHashMap而是使用组合,因为这会限制您公开的方法。


例如

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

关于java - 扩展LinkedHashMap时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38305411/

10-10 03:24