问题
I have an object that contains an array, but the type of the array will be diffent every time.
I could do something like
class MyObject<T>
{
public T [] data;
}
The thing is that this does not work with primitive types (int, double, ...) and it makes me work with Objects (Integer, Double...).
Is there any way of avoiding this?
Thanks in adavnce
回答1:
You should be aware that autoboxing in Java may do exactly what you're looking for. See this code example from the link:
// List adapter for primitive int array
public static List<Integer> asList(final int[] a) {
return new AbstractList<Integer>() {
public Integer get(int i) { return a[i]; }
// Throws NullPointerException if val == null
public Integer set(int i, Integer val) {
Integer oldVal = a[i];
a[i] = val;
return oldVal;
}
public int size() { return a.length; }
};
}
That get()
method is returning a plain old data type int
that is automatically converted into an Integer
. Likewise, the set()
method is taking an Integer
and assigning an int
element in the array.
Autoboxing is not an immediately obvious feature but it does handle the automatic object creation.
回答2:
You can't use primitives in generics, like you can in C++ with Templates.
If you want a collection which uses primitives I suggest you look at http://trove.starlight-systems.com/ You can pass this collection type as part of the generic. i.e. instead of passing the primitive type, pass the collection type.
MyObject<List<String>> containsStrings = ...
MyObject<TIntArrayList> contains_ints = ...
回答3:
This isn't possible. Convert primitive arrays to their OO equivalents.
来源:https://stackoverflow.com/questions/5910584/how-can-we-work-with-generic-types-and-primitives-in-java