代码之家  ›  专栏  ›  技术社区  ›  Lumpy

无集合的泛型

  •  4
  • Lumpy  · 技术社区  · 16 年前

    myMethod(T item)
    

    我想用这个方法,但我知道我发送的方法。

    SpecificItem myItem = new SpecificItem();
    
    myMethod((T) myItem);
    

    我不喜欢这个。这是坏代码的迹象吗?

    5 回复  |  直到 16 年前
        1
  •  9
  •   Andreas Dolk    16 年前

    myMethod 在泛型类中定义,类似于:

    public class MyClass<T> {
       T myItem;
    
       public void myMethod(T item) {
          // do Something with item
       }
    
       public T myOtherMethod() {
          myMethod(myItem);   // casting is not necessary
          return myItem;
       }
    
    }
    

    T

    MyClass<SpecificItem > concreteClass = new MyClass<SpecificItem >();
    

    如果你打电话 我的方法 SpecificItem ,因为 是此实例的泛型类型。

        2
  •  2
  •   Hendra Jaya    16 年前

    最好是编写接口代码。例如:

    在myMethod中:

    <T extends <? super Item>> void (T item);
    

    这告诉编译器只接受T的泛型类型,它是项接口/类的实现/扩展。这将确保给定的输入是正确的类型。编译器保证。

    Item myItem = new SpecificItem();
    

    上面给出的代码是最佳实践。习惯吧。但是(我不鼓励这样做)您也可以这样编写代码:

    SpecificItem myItem = new SpecificItem();
    

    您可以阅读Java源代码。例如在课堂上java.util.Collections文件. In方法 sort(List) 您可能注意到,joshuabloch确保给定的输入总是以正确的格式。要尝试一下,请执行以下操作:

    public class Class1 {
        public static void main(String[] args) {
            List<Class1> list = new ArrayList<Class1>();
    
            Collections.sort(list);
        }
    }
    

    哦,我差点忘了你的问题。事实上,这是一个不错的代码,因为它的工作。我只想告诉你有更好的办法。

        3
  •  1
  •   Allain Lalonde    16 年前

    你可能在找这样的东西:

    class C<? extends T> {
    
       public void myMethod(T myItem) {
          ...
       }
    
    }
    
        4
  •  1
  •   D_K    16 年前
        5
  •  0
  •   Drew    16 年前