一个java泛型编程问题

时间:2011-09-09 15:51:10

标签: java

我有这样的A类:

public class A<T extends Number>
{
 ....
}

在另一个班级,我有这个方法:

public Hashtable<String, A> createAHashtable()
    {
        Hashtable<String, A> hTable = new Hashtable<String, A>();

        return hTable;
    }

参数A有警告,因为它是泛型类。我应该这样做:

public Hashtable<String, A <?>> createAHashtable()
        {
            Hashtable<String, A<?>> hTable = new Hashtable<String, A<?>>();

            return hTable;
        }

或者这样做:

public Hashtable<String, A <? extends Number>> createAHashtable()
{
Hashtable<String, A<? extends Number> hTable = new Hashtable<String, A<? extends Number>();

return hTable;
}

或.... ???

修改

试过这个(按照Dilum的建议)

public <T extends Number> Hashtable<String, A<T>> createAHashtable()
    {
        Hashtable<String, A<T>> hTable = 
                new Hashtable<String, A<T>>();
        A<Float> constraint = new A<Float>();
        hTable.put("test", constraint);

        return hTable;
    }

但是“放”我的Float A是无效的。

也许通配符是可行的方法。

编辑2:

根据Dilum的建议,下面的代码(当将一个Float A放入Hashtable时转换为A)没有错误,但警告它是不安全的转换。为什么我们需要演员呢?

public <T extends Number> Hashtable<String, A<T>> createAHashtable()
        {
            Hashtable<String, A<T>> hTable = 
                    new Hashtable<String, A<T>>();
            A<Float> constraint = new A<Float>();
            hTable.put("test", (A<T>)constraint);

            return hTable;
        }

2 个答案:

答案 0 :(得分:5)

试试这个:

public <T extends Number> Hashtable<String, A<T>> createAHashtable() {
  return new Hashtable<String, A<T>>();
}

假设您确实要预先填写键值对,请尝试:

public <T extends Number> Hashtable<String, A<T>> createAHashtableWithEntry(String key, T value) {
  Hashtable<String, A<T>> ht = return new Hashtable<String, A<T>>();
  ht.put(key, new A<T>(value));
  return ht;
}

答案 1 :(得分:0)

与编辑2相关:

以下是案件不安全的具体例子。在我的IDE上,我实际上甚至没有得到关于演员表不安全的警告。

import java.util.ArrayList;
import java.util.List;

public class Genericss {

   static <T extends Number> List<A<T>> get2() {
      List<A<T>> list = new ArrayList<A<T>>();
      A<Float> f = new A<Float>(3.0f);
      list.add((A<T>) f); // Compiles... not even a warning on my IDE
      return list;
   }

   public static void main(String[] args) {
      List<A<Integer>> l = Genericss.<Integer>get2();
      Integer i = l.get(0).get(); // runtime error

      A<Float> f = new A<Float>(3f);
      //i = (A<Integer>) f;  // won't compile
   }

   public static class A<T> {
      T t;

      public A(T t) {
         this.t = t;
      }

      public T get() {
         return t;
      }
   }
}