I have two methods that make the same thing, but one receives a HashMap<Integer,double[]>
and the other receive a HashMap<Integer,int[]>
. How can I make this without to duplicate code.
Asked
Active
Viewed 40 times
-2

fmassica
- 1,896
- 3
- 17
- 22
-
2You could convert to `Map
`, but that would involve changing callers of the method and Object overhead. Guess, there's no better way, though. – qqilihq Oct 11 '14 at 19:56 -
1The code you posted won't even compile, you need to use `Integer[]` instead of `int[]` – msrd0 Oct 11 '14 at 19:57
-
@msrd0 Why should this not compile? – qqilihq Oct 11 '14 at 19:58
-
3@msrd0 a primitive array is an `Object`, and thus eligible as a type argument. It compiles just fine. – Mureinik Oct 11 '14 at 19:59
-
@qqilihq Because Java doesn't allow types like `int` or `double` to be templates. You always need the wrapper classes like `Integer` or `Double` – msrd0 Oct 11 '14 at 19:59
-
@msrd0 Not true. Arrays are Objects. – qqilihq Oct 11 '14 at 19:59
-
@Mureinik Really? Thought this causes an error ... – msrd0 Oct 11 '14 at 19:59
-
I'm gonna try replace Map
for Map – fmassica Oct 11 '14 at 20:00.
1 Answers
0
Make two methods, one contains the real code, acception the version with the double-array and the other method, accepting the integer-version just calls this method but first converts the integer-array to a double array.
public void doSomething(HashMap<Integer, int[]> arg0) {
//convert int[] to double[] and fill this HashMap
HashMap<Integer, double[]> converted;
doSomething(converted);
}
public void doSomething(HashMap<Integer, double[]> arg0) {
//your logic here
}

rogi1609
- 438
- 3
- 8
-
-
-
-
this will never work!`doStuff(HashMap
) and doStuff(HashMap – Oct 11 '14 at 21:11) have the same erasure`