Reputation: 356
I got this ArrayTools class which does a number of array operations on a integer array.
public class ArrayTools {
private int arr[];
/* other variables */
public ArrayTools(int max) {
arr = new int[max];
/* other stuff */
}
At the moment all the methods of that class take that integer array to work with.
Now I need to implement exactly same methods for a float array. I obviously don't want to c&p the whole code into a new ArrayToolsFloat class changing 'int' into 'float' being this the only difference between them. I guess the "right" way is to overload the methods, therefor I wrote a new constructor:
private int integerArray[];
private float floatArray[];
/* constructor which creates the type of array based on the input of the second parameter */
public ArrayTools(int max, String arrayType) {
if (arrayType.equals("float")) {
floatArray = new float[max];
} else if (arrayType.equals("int")){
integerArray = new int[max];
}
Now the problem is that I can't find out how to use the array in a generic way. My methods still don't know which array was created and I don't want to call them with a parameter which specifies that. Doesn't seem to make sense. The constructor doesn't let me declare the private vars inside. Otherwise I would do this:
if (arrayType.equals("float")) {
private float genericArray = new float[max];
} else if (arrayType.equals("int")){
private int genericArray = new int[max];
}
Upvotes: 1
Views: 1366
Reputation: 3694
Use Float and Integer objects and implement it using generics.
public class ArrayTools<T>{
private List<T> arr;
public ArrayTools(int max) {
arr = new ArrayList<T>(max);
/* other stuff */
}
}
to use that class you simply can do it in that way
ArrayTools<Float> floatArrayTools = new ArrayTools<Float>(max);
ArrayTools<Integer> floatArrayTools = new ArrayTools<Integer>(max);
Upvotes: 3