No, you can't overload methods like that. You would have to give them different names. They do different things, so it would be more appropriate to call them parseCollectionToString or parseCollectionToDouble or similar. And do you mean to return a double or a Double?
It is difficult to be certain; I haven't seen your code, but . . .
I don't think duplication will affect performance.
If you are casting the output to different types, you can't regard those methods as overloaded because they have the same signature and different return types.
Pulling out common code into a third method sounds a very good idea.
The method parse at the end typecasts it . Only thing i am worried is about the duplication of code. There is one possibility to move the common things to one method.
But is there any other way.
Yes you can have one additional parameter being passed to parse method (say boolean), to indicate the instance to be returned.
But again that will cause problem if at a later stage you want to return a Long from the same method. (though you can use String as the third argument in that case)
Kowshik Nandagudi wrote:
Also does duplication of the code affect the performance ?
Thanks in advance
Yes when class is loaded, the methods are also loaded into the memory by JVM.
Sunny Bhandari wrote: . . . Yes you can have one additional parameter being passed to parse method (say boolean), to indicate the instance to be returned. . . .
Look at methods like List#toArray(T) and see how they use generics to alter the return type. You might be able to use a generic method, which I really ought to have thought of earlier. Better approach than using a boolean for return type.
. . . Yes when class is loaded, the methods are also loaded into the memory by JVM.
Do you think that will make a noticeable difference to performance?
Talking about the common method I think it would be better if you have something like this
Common method - parseCollection() - this has the logic to parse the collection passed as input.
Specific methods - parseCollectionToString() and parseCollectionToDouble() that just typecasts the result returned from parseCollection() and return back the specific type.
This will also help you in future in case you need to extend the parsing to different data types.