遇到了我無法解決的泛型和數組類型問題。歸結到這一點。在下面的代碼中,如何將通用列表轉換爲具有相同通用類型的數組,同時使用工廠方法(「T convert(String value)」)來轉換輸入通用列表中的每個單獨元素:Java泛型和數組類型
@Test
public void test(){
List<String> integers = Arrays.asList("1", "2", "3", "4");
Integer[] integerArray = new TypeConverter<Integer[]>(Integer[].class).convert(integers);
assertEquals(4, integerArray.length);
assertEquals(1, integerArray[0].intValue());
assertEquals(2, integerArray[1].intValue());
assertEquals(3, integerArray[2].intValue());
assertEquals(4, integerArray[3].intValue());
}
public class TypeConverter<T>{
Class<T> type;
public TypeConverter(Class<T> type) {
this.type = type;
}
T convert(List<String> values){
List output = new ArrayList();
for (String value : values) {
//have to use Object.class here since I cant get the non-array type of T:
output.add(new TypeConverter(type.getComponentType()).convert(value));
}
return (T) output.toArray();
}
T convert(String value){
//convert to an int;
if(type == Integer.class){
return (T) new Integer(Integer.parseInt(value));
}
return null;
}
}
正如你看到的,我天真的做法是簡單地使用指定者的方法,並把結果像這樣:
(T) value.toArray()
但這會導致一個ClassCastException:
的java.lang .ClassCastException:[L java.lang.Object繼承;不能投到[Ljava.lang.Integer
有沒有辦法解決這個問題,我沒有看到,或者我應該採取另一種方法?
編輯
這裏,我試圖解決具體的代碼。具體的visitArray()方法:
可能重複[?List類的指定者:Java的,爲什麼我不能的「整數」列表轉換成「整數」陣列(HTTP://計算器.COM /問題/ 7281793 /列表班組長-指定者功能於Java的,爲什麼-着-I-轉換-A-列表的整數到一個-INT) –
其實我提交我的職務之前閱讀該文章。我的問題不是重複的,因爲我在詢問有關數組的泛型。 –