簡體   English   中英

將數據添加到java中的泛型集合中

[英]Add data to a generic collection in java

有什么辦法可以將數據添加到Java中的泛型集合中。 例如: -

import java.util.List;
import java.util.Vector;

public class testGenerics {
    public static void main(String args[]) {    
        Vector<? extends Number> superNumberList = null;

        // I can do this
        Vector<Integer> subList = new Vector<Integer>();
        subList.add(2);
        superNumberList = subList;

        // But i cannot do this
        // Gives the below compilation error.
        //The method add(capture#2-of ? extends Number) in the type 
        //Vector<capture#2-of ? extends Number> is not applicable for the arguments (Integer)        
        superNumberList = new Vector<Integer>();
        superNumberList.add(new Integer(4));

        superNumberList = new Vector<Float>();
        superNumberList.add(new Float(4));
    }

}

正如我在評論中提到的,當我嘗試將一個Integer或Float數據添加到superNumberList時,我有編譯錯誤。

我能夠做到這一點,第一種方式,但我想第二種方式,並不確定為什么Java不允許我做第二種方式。

我有一個西裝,我有一個超類,它有這個superNumberList,所有的子類都試圖使用這個相同的變量,但在這個集合中有不同的數據類型,如Integer,Float等。

一個Vector<? extends Number> Vector<? extends Number>是未知Number類型的Vector。 因此,您無法在其中添加任何內容。

它可能是Vector<Float> 所以你不能添加一個Integer

但它也可能是Vector<Integer> 所以你不能添加Float

你唯一知道的是,無論你 Vector中取出什么都是一個Number


如果你有一個具有IntegerFloat等子類的超類,你應該使超類具有通用性:

class SuperClassWithVector<T extends Number>{
    protected Vector<T> myVector;
}

class FloatSubClass extends SuperClassWithVector<Float>{
   // here myVector takes Float
}

如果你想要一個可以同時使用IntegerFloatVector (不確定這是否是你想要的),那么你可以使用Vector<Number>

你不需要使用? extends Number ? extends Number

Vector<Number> superNumberList = null;
...
superNumberList = new Vector<Number>();
superNumberList.add(new Integer(4));
superNumberList.add(new Float(4));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM