Java Generics无法正常工作

为什么generics不能在我的机器上工作。 为什么下面的代码不能在没有类型转换为String Eclipse中工作。 我使用的是Java 1.6

 package com.withgeneric; class Util { // Generic static method public static  boolean compare(Pair p1, Pair p2) { return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue()); } } class SPair { private K key; private V value; // Generic constructor public SPair(K key, V value) { this.key = key; this.value = value; } // Generic methods public void setKey(K key) { this.key = key; } public void setValue(V value) { this.value = value; } public K getKey() { return key; } public V getValue() { return value; } } public class GenericMethod { /** * @param args */ public static void main(String[] args) { Pair p1 = new SPair(1, "apple"); //Giving Error Pair p2 = new SPair(2, "pear"); //Giving Error boolean same = Util.compare(p1, p2); // TODO Auto-generated method stub } } 

在eclipse中,转到Window> Preferences> Java> Compiler并查找JDK合规性。 确保它至少为1.5。

从Java 1.5开始,这无需投射。

 package java.util; public interface List extends Collection { .... E get(int index); .... } 

也许有用: Java Generics

如果您使用的是Java 1.5或更高版本,则此语句不会出现任何错误。 但是如果你使用的是旧版本而不是

 List list = new ArrayList(); 

会给出错误。 首先,你必须解决这个问题,而不是类型转换。

你检查过eclipse项目中配​​置的JVM吗? 转到配置构建路径,然后检查是否包含正确的库

编写一个完整的程序,其中包含您在上面发布的行。 不要复制并粘贴它们,全部输入。包括java程序所需的行,即public static void main (String[] args)等。对该程序执行’clean’和’build’,并告诉它我们整个结果。 如果仍然导致错误,请发布整个程序和整个错误。

还要注意,很难(最多)弄清楚另一台机器的配置有什么问题而不能看到它; 帮助我们获取有关内容的信息。 突然的答案使它看起来像是你希望我们修复的Java。