问题
So I'm working on an implementation of a Grid class for a small, personal utilities library. After much work, I'm tidying up the Grid class and adding some functionality. One of the key pieces of functionality that I wish to use with my Grid class is to be able to take a single, 2D array of any given type as an argument to the constructor.
This worked fine until I realized that I can't compile any code that attempts to pass in any array of primitives to the constructor. Since autoboxing doesn't happen on primitive arrays, this presents a design problem to me in the form of code reuse. The method for initializing the Grid is the same regardless of the type of array passed in, even if they are primitives, but it appears that I need to write a separate constructor for all the different types of primitives. Which leaves me with 9 different constructors assuming I just use my base constructor (and I had planned to have constructors with different arguments for things such as grid-wrapping options).
Am I right in assuming that there is no way to avoid all this code duplication?
回答1:
You can avoid (most of) the duplication by using Array
class. But it's not pretty: your constructor parameter would have do be of type Object
, and you'd have to just trust your caller to pass the actual array there, and not a Socket
or a Properties
.
For example, you could do your own boxing like this:
<T> public T[][] boxArray(Class<T> clazz, Object array) {
int height = Array.getLength(array);
int width = height == 0 ? 0 : Array.getLength(Array.get(array, 0));
T[][] result = (T[][]) Array.newInstance(clazz, height, width);
for(int i = 0; i < height; i ++) {
Object a = Array.get(array, i);
for(int j = 0; j < width; j++) {
result[i][j] = (T) Array.get(a, j);
}
}
return result;
}
来源:https://stackoverflow.com/questions/27715595/java-generics-method-code-duplication-issue-regarding-primitive-arrays