代码之家  ›  专栏  ›  技术社区  ›  Igor Zelaya

为什么不能在Java中创建泛型填充方法?

  •  2
  • Igor Zelaya  · 技术社区  · 17 年前

    abstract class DTO{ }
    
    class SubscriptionDTO extends DTO { }
    

    protected void fillList(ResultSet rs, ArrayList<? extends DTO> l)
            throws BusinessLayerException {
        SubscriptionDTO bs;
        try {
            while (rs.next()){
                //initialize bs object...
                l.add(bs); //compiler error here
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    
    }
    

    3 回复  |  直到 17 年前
        1
  •  7
  •   Community Mohan Dere    9 年前

    您应该使用 <? super DTO> <? super SubscriptionDTO> Tom Hawtin - tackline ArrayList .

    从第28项开始 Effective Java sample chapter

    T <? extends T> T 消费者,使用 <? super T> .

    l <

        2
  •  2
  •   Henrik Paul    17 年前

    Foo extends Bar Zoo extends Bar

    List<Foo> fooList = new ArrayList<Foo>();
    fooList.addAll(aBunchOfFoos());
    aMethodForBarLists(fooList);
    

    void aMethodForBarLists (List<? extends Bar> barList) {
       barList.add(new Zoo());
    }
    

    List<Foo>

    <? extends Something> 似乎

        3
  •  2
  •   alasdairg    17 年前

    protected void fillList( ResultSet rs, List<DTO> l ) throws BusinessLayerException 
    {
       SubscriptionDTO bs;
       try 
       {
          while   ( rs.next() )
          {
             //initialize bs object...
             l.add( bs );
          }
        }
        catch ( SQLException e ) 
        {
           e.printStackTrace();
        }
    

    }