kbluue
kbluue

Reputation: 379

How to create a method that can take in multiple classes as input

Take for example:

public static String[] multipleOfSameSet(String var,int setLength){
    String[] out = new String[setLength];
    for(int i=0; i<setLength; i++){
        out[i] = var;
    }
    return out;
}

but I want this to work for int, double and about 10 other classes. I tried using a class in place of String and it gave me a world of errors. Here:

Is it even possible?? If yes, how do I do it?

Upvotes: 1

Views: 2079

Answers (2)

Wander Nauta
Wander Nauta

Reputation: 19615

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 Integers, doubles become Doubles 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);
}

Upvotes: 4

Constantin
Constantin

Reputation: 1506

You can use interfaces or defined class types..

public static MyInterface[] multipleOfSameSet(MyInterface var, int setLength) {
    MyInterface[] out = new MyInterface[setLength];
    for(int i = 0; i < setLength; i++) {
        out[i] = var;
    }
    return out;
}

Upvotes: 0

Related Questions