<E> 以及<Object>差异和用法



有人可以解释一下,例如在list类中使用E或Object有什么不同,以及它们的单一用法和定义。我必须在LinkedLists中使用它们来实现方法。

假设E来自element,当编译的方法说它接受一个特定类型的数组,并返回一个相同类型的数组时,我将考虑在Collections中使用泛型。

另一方面,你不能把橙子和苹果混在一起。如果可以将字符串列表传递给需要对象列表的方法,则可以将对象添加到字符串列表中。(并不是所有的对象都是字符串)

您编写的语法为引用泛型

泛型提供了一种方法,可以对不同的数据类型重用相同的代码泛型,同时在编译时仍然保持严格的类型检查。例如,正如您所提到的,如果使用数据结构处理Object类型的元素,那么在添加或获取其元素时就没有类型安全性,因为可以传递并从中检索任何类实例。这将导致容易出错的代码,其中从数据结构中检索到的元素应该首先转换为预期的数据类型才能使用,或者在最坏的情况下不是正确的类型,并且只有在运行时才知道这一点,没有办法防止它。

正因为如此,泛型帮助开发人员允许他/她为每种不同的情况建立泛型类型形参和特定的类型实参(非基本类型)。这不仅为您的代码提供了更多的灵活性和可重用性,而且一旦您建立了泛型类型参数E代表特定的数据类型(Integer, String或其他),那么编译器将确保您的对象将使用类型参数E执行的每个操作都将符合您指定的类型参数
public class Test {
public static void main(String[] args) {
//Here I can add mixed non-primitive types because they're also instances of Object and therefor compliant to the expected type
List listObj = new ArrayList();
listObj.add(Integer.valueOf(5));
listObj.add("Hello");
listObj.add(Double.valueOf(3.77));
//Here I can't retrieve the elements with their right type even though I know I've placed an Integer, a String and a Double in its first, second and third position
Integer i1 = listObj.get(0);
String s1 = listObj.get(1);
Double d1 = listObj.get(2);


//Here I'm defining a generic list working only with Integer (for this specific instance)
List<Integer> listGenInt = new ArrayList<>();
listGenInt.add(Integer.valueOf(5));
//If I try to add any other type but Integer I'd get an error at compile time
listGenInt.add("Hello");
listGenInt.add(Double.valueOf(3.77));

//Here I can only expect to retrieve elements of the data type I've established for this object during its declaration (Integer)
Integer i2 = listGenInt.get(0);
//Here I'd get an error If I'd try read its elements with any data type but Integer
String s2 = listGenInt.get(1);
Double d2 = listGenInt.get(2);

//Here I'm defining a generic list working only with String (for this specific instance)
List<String> listGenStr = new ArrayList<>();
listGenStr.add("Hello");
//If I try to add any other type but String I'd get an error at compile time
listGenStr.add(Integer.valueOf(5));
listGenStr.add(Double.valueOf(3.77));
//Here I can only expect to retrieve elements of the data type I've established for this object during its declaration (String)
String s3 = listGenStr.get(1);
//Here I'd get an error If I'd try read its elements with any data type but String
Integer i3 = listGenStr.get(0);
Double d3 = listGenStr.get(2);
}
}

在这里,还有一个链接,其中有来自Oracle官方教程的示例和进一步的解释。

https://docs.oracle.com/javase/tutorial/extra/generics/intro.html

最新更新