问题:

Java中的原始类型是什么?为什么我经常听到不应该在新代码中使用它们?如果我们不能使用原始类型,还有什么替代方法?如何更好?


当前回答

简单综合一下:原始类型是一个没有类型参数的泛型类型(例如:List是List<E>的原始类型),不应该使用原始类型。它们的存在是为了与旧版本的Java兼容。我们希望尽快(编译时)发现错误,使用原始类型可能会在运行时导致错误。在两种情况下,我们仍然需要使用原始类型:

类文字的用法(List.class)instanceof的用法

示例:

//Use of raw type : don't !
private final Collection stamps = ...
stamps.add(new Coin(...)); //Erroneous insertion. Does not throw any error
Stamp s = (Stamp) stamps.get(i); // Throws ClassCastException when getting the Coin

//Common usage of instance of
if (o instanceof Set){
    Set<?> = (Set<?>) o;
}

其他回答

 private static List<String> list = new ArrayList<String>();

您应该指定类型参数。

警告建议,应将定义为支持泛型的类型参数化,而不是使用其原始形式。

List被定义为支持泛型:公共类List<E>。这允许在编译时检查许多类型安全操作。

在这里,我考虑了多个案例,通过这些案例,你可以明确概念

1. ArrayList<String> arr = new ArrayList<String>();
2. ArrayList<String> arr = new ArrayList();
3. ArrayList arr = new ArrayList<String>();

案例1

ArrayList<String>arr它是一个类型为String的ArrayList引用变量,它引用的是一个字符串类型的ArralyList对象。这意味着它只能保存String类型的Object。

它是一个Strict to String,而不是Raw类型,因此它不会引发警告。

    arr.add("hello");// alone statement will compile successfully and no warning.

    arr.add(23);  //prone to compile time error.
     //error: no suitable method found for add(int)

案例2

在这种情况下,ArrayList<String>arr是一个严格类型,但您的Object new ArrayList();是原始类型。

    arr.add("hello"); //alone this compile but raise the warning.
    arr.add(23);  //again prone to compile time error.
    //error: no suitable method found for add(int)

这里arr是严格类型。所以,当添加整数时,它会引发编译时错误。

警告:-原始类型对象引用到ArrayList的严格类型引用变量。

案例3

在本例中,ArrayList arr是一个原始类型,但Object new ArrayList<String>();是严格类型。

    arr.add("hello");  
    arr.add(23);  //compiles fine but raise the warning.

它将向其中添加任何类型的对象,因为arr是一种原始类型。

警告:-严格类型对象引用到原始类型引用的变量。

Java中的原始类型是什么?为什么我经常听到不应该在新代码中使用它们?

原始类型是Java语言的古老历史。最初有集合,它们只持有对象。对集合的每个操作都需要将对象强制转换为所需类型。

List aList = new ArrayList();
String s = "Hello World!";
aList.add(s);
String c = (String)aList.get(0);

虽然这在大多数时间都有效,但确实发生了错误

List aNumberList = new ArrayList();
String one = "1";//Number one
aNumberList.add(one);
Integer iOne = (Integer)aNumberList.get(0);//Insert ClassCastException here

旧的无类型集合无法强制执行类型安全,因此程序员必须记住他在集合中存储的内容。泛型是为了克服这个限制而发明的,开发人员只需声明一次存储的类型,编译器就会改为声明。

List<String> aNumberList = new ArrayList<String>();
aNumberList.add("one");
Integer iOne = aNumberList.get(0);//Compile time error
String sOne = aNumberList.get(0);//works fine

用于比较:

// Old style collections now known as raw types
List aList = new ArrayList(); //Could contain anything
// New style collections with Generics
List<String> aList = new ArrayList<String>(); //Contains only Strings

Comparable接口更复杂:

//raw, not type save can compare with Other classes
class MyCompareAble implements CompareAble
{
   int id;
   public int compareTo(Object other)
   {return this.id - ((MyCompareAble)other).id;}
}
//Generic
class MyCompareAble implements CompareAble<MyCompareAble>
{
   int id;
   public int compareTo(MyCompareAble other)
   {return this.id - other.id;}
}

请注意,无法使用原始类型的compareTo(MyCompareAble)实现CompareAbble接口。为什么不应该使用它们:

存储在集合中的任何对象都必须在使用之前进行强制转换使用泛型启用编译时检查使用原始类型与将每个值存储为Object相同

编译器的作用:泛型是向后兼容的,它们使用与原始类型相同的java类。神奇之处主要发生在编译时。

List<String> someStrings = new ArrayList<String>();
someStrings.add("one");
String one = someStrings.get(0);

将编译为:

List someStrings = new ArrayList();
someStrings.add("one"); 
String one = (String)someStrings.get(0);

这与直接使用原始类型时编写的代码相同。虽然我不确定CompareAble接口会发生什么,但我猜它会创建两个compareTo函数,一个接受MyCompareAbl,另一个接受Object并在强制转换后将其传递给第一个。

原始类型的替代方法是什么:使用泛型

编译器希望您编写以下内容:

private static List<String> list = new ArrayList<String>();

因为否则,您可以将任何您喜欢的类型添加到列表中,使实例化为新的ArrayList<String>()变得毫无意义。Java泛型只是一个编译时特性,因此,如果将新的ArrayList<String>()创建的对象分配给“原始类型”List的引用,它将欣然接受Integer或JFrame元素-对象本身不知道应该包含什么类型,只有编译器知道。

这是另一种生肉会咬你的情况:

public class StrangeClass<T> {
  @SuppressWarnings("unchecked")
  public <X> X getSomethingElse() {
    return (X)"Testing something else!";
  }

  public static void main(String[] args) {
    final StrangeClass<String> withGeneric    = new StrangeClass<>();
    final StrangeClass         withoutGeneric = new StrangeClass();
    final String               value1,
                               value2;

    // Compiles
    value1 = withGeneric.getSomethingElse();

    // Produces compile error:
    // incompatible types: java.lang.Object cannot be converted to java.lang.String
    value2 = withoutGeneric.getSomethingElse();
  }
}

这是反直觉的,因为您希望原始类型只影响绑定到类类型参数的方法,但实际上它也影响具有自己类型参数的泛型方法。

正如在公认的答案中所提到的,您将失去对原始类型代码中泛型的所有支持。每个类型参数都转换为其擦除(在上面的示例中,它只是Object)。