2016-05-22 71 views
0

我最近開始學習Java,並具有與使用泛型的問題。我使用的參數和參數上界NumberBox<T extends Number>類只會儲存Number對象並對它們進行比較。每當我試圖創建未知List<NumberBox<?>>存儲任何NumberBox<T extends Number>對象的列表,我不能添加一個List<NumberBox<Short>>使用非參數方法static addList(List<NumberBox<?>> destinationList, List<NumberBox<?>> sourceList)未知數這個名單。不過,我可以在這個參數列表添加到使用參數方法<T extends Number> static addListInference(List<NumberBox<?>> destinationList, List<NumberBox<T>> sourceList)未知的列表。任何幫助表示讚賞。謝謝。無法添加列表<SomeClass的<邊界類型SomeClass的>>的孩子列表<SomeClass<?>>

import java.util.*; 
import java.lang.*; 
import java.io.*; 

interface Box<T> { 
    public T get(); 
    public void set(T t); 
    public int compareTo(Box<T> other); 
} 

class NumberBox<T extends Number> implements Box<T> { 
    T t; 
    public NumberBox(T t) { 
     set(t); 
    } 
    @Override 
    public T get() { 
     return t; 
    } 
    @Override 
    public void set(T t) { 
     this.t = t; 
    } 
    @Override 
    public int compareTo(Box<T> other) { 
     int result = 0; 
      if (t.doubleValue() < other.get().doubleValue()) { 
       result = -1; 
      } else if (t.doubleValue() > other.get().doubleValue()) { 
       result = 1; 
      } else if (t.doubleValue() == other.get().doubleValue()) { 
       result = 0; 
      } 
     return result;  
    } 
} 


class MainClass { 

    public static <T extends Number> 
    void addListInference(List<NumberBox<?>> destinationList, List<NumberBox<T>> sourceList) { 
     destinationList.addAll(sourceList); 
    } 

    public static void addList(List<NumberBox<?>> destinationList, 
    List<NumberBox<?>> sourceList) { 
     destinationList.addAll(sourceList);  
    } 

    public static void main (String[] args) throws java.lang.Exception { 
     // your code goes here 
     List<NumberBox<?>> list = new ArrayList<>(); 
     List<NumberBox<Short>> shortList = new ArrayList<>(); 
     shortList.add(new NumberBox<Short>((short) 1)); 
     // this one fails 
     MainClass.addList(list, shortList); 
     // this one works 
     MainClass.addListInference(list, shortList); 
    } 
} 
+0

旁白:你'compareTo'方法將作爲'返回Double.compare(t.doubleValue(),other.get更簡單地實現().doubleValue());'。 –

+0

是的,我不知道Double.compare(雙,雙)用於冗餘雜波存在遺憾。 –

回答

1

的問題是,

List<NumberBox<?>> 

List<NumberBox<Short>> 

因爲List<Superclass>List<Subclass>超類的父類。

你可以把它沒有類型的變量T使用工作:

List<? extends NumberBox<?>> 
+0

感謝您的信息,目前所做的更改它的工作原理。 –

相關問題