Yes, it's possible. One option is to try and find a class that is a superclass of all the classes you want to use, or an interface all your classes implement. In your case, the only candidate might be Object:
public static Object[] multipleOfSameSet(Object var, int setLength) {
Object[] out = new Object[setLength];
for(int i = 0; i < setLength; i++) {
out[i] = var;
}
return out;
}
This will work, because all Java classes extend Object, either directly or indirectly. Primitive values get converted into objects automaticaly (ints become Integer
s, doubles become Double
s and so on).
The downside of this approach is that, well, you get an array of Objects back, and there's not much you can do with those. What you might want to consider instead is making your method accept some generic type T, and returning an ArrayList of T's:
public static <T> ArrayList<T> multipleOfSameSet(T object, int setLength) {
ArrayList<T> out = new ArrayList<T>();
for(int i = 0; i < setLength; i++) {
out.add(object);
}
return out;
}
However, if you don't need to modify the list afterwards, I'd go with this:
public static <T> List<T> multipleOfSameSet(T object, int setLength) {
return Collections.nCopies(setLength, object);
}