0

How to use only one method for any data type

https://code.sololearn.com/cwKAoMXo7tbZ/?ref=app here, I have made a class with a random function that takes an array argument and returns a random element of that array. Is there a better way to write, without having to overload for different data types?

7th Nov 2021, 6:26 AM
4C$
4C$ - avatar
8 Answers
+ 2
Edited: You can try to generify your static random method in your Select class. That way you can use one method for any data type without explicitly instantiating the Select class. https://code.sololearn.com/cSaJ35IUAz2I/?ref=app
7th Nov 2021, 7:24 AM
Anannya
+ 2
【4C$】 you're welcome. I'll still follow this thread to see if someone else can come up with better solutions.. šŸ˜…
7th Nov 2021, 8:22 AM
Anannya
+ 1
Sigag Thanks, Is it possible to use the static method of generic class, so that we don't have to explicitely instantiate or state the data type.
7th Nov 2021, 7:36 AM
4C$
4C$ - avatar
+ 1
Sigag Thanks a lot, ur code have been really helpful.
7th Nov 2021, 8:19 AM
4C$
4C$ - avatar
+ 1
Martin Taylor Thank you for your input! Your contribution to community has always been very helpful! Actually the OP asked "..without having to overload for different data types" I couldn't understand how to do it for primitive types so did it for reference types instead šŸ˜… Is there any way to achieve this for primitive types without using overloaded methods?
8th Nov 2021, 2:30 AM
Anannya
+ 1
Martin Taylor thanks, I saw the API for Arrays.binarySearch, was surprised to see overloading for different data types.
8th Nov 2021, 2:50 PM
4C$
4C$ - avatar