0

I am learning java, and I have got around to the topic of Generics and raw types. I have found that I had been using some library classes in Java which are generic (didn't know it before), and I had been using them as if they are just normal classes (declaring them like a normal object). Will that lead to the raw types? And since raw types are said to be avoided, should I, before using any of the library classes or interfaces of Java, make sure whether they are generic or not? And if a class is generic then use it as it meant to (parameterized type)?

4

2 回答 2

1

如果一个类是这样声明的:

public class MyClass<T>

你像这样使用它:

MyClass myVariable = new MyClass();

那么是的,它确实是一个原始类型,你不应该使用它。集合类(如ArrayList)在 Java 5+ 上是泛型的,当它可用时,您应该始终使用泛型变体。观察编译器警告;他们通知使用泛型,除其他外。

于 2012-07-13T05:22:06.813 回答
0

看看这个示例类:

class Queue<T> {
   private LinkedList<T> items = new LinkedList<T>();
   public void enqueue(T item) {
      items.addLast(item);
   }
   public T dequeue() {
      return items.removeFirst();
   }
   public boolean isEmpty() {
      return (items.size() == 0);
   }
}

这是一个类型为 T 的泛型类。您可以构建一个类的实例,该类的任何类型都需要与内部使用的类型相关联。

如果您想使用 Integer 类型,您可以按如下方式实例化该类,例如:

Queue<Integer> queue = new Queue<Integer>();

您还可以在一个类中使用多个类型,如下所示:

class Pair<T,S> {
   public T first;
   public S second;
   public Pair( T a, S b ) {
      first = a;
      second = b;
   }
}

并像这样实例化它:

Pair<String,Color> colorName = new Pair<String,Color>("Red", Color.RED);

或者像这样:

Pair<Double,Double> coordinates = new Pair<Double,Double>(17.3,42.8);
于 2012-07-13T05:36:29.640 回答