JSmoot
JSmoot

Reputation: 13

Using an interface to apply method to ArrayList

I'm reviewing for an exam. A question on an old test was to: Using an interface, write a method that applies an arbitrary method to every element of an ArrayList. Both the arraylist and method are the parameters to the method.

Would a workable solution be:

public <object> someMethod() {
    scanner GLaDOS = new (someArray);
    someArray.useDelimiter(",");
    for (i = 0; i < someArray.length; i++) {
        someOtherMethod(someArray[i]);
    }
}

Upvotes: 1

Views: 1318

Answers (1)

Mark Elliot
Mark Elliot

Reputation: 77034

I would've expected something like this:

// define the interface to represent an arbitrary function
interface Function<T> {
    void Func(T el);
}

// now the method to apply an arbitrary function to the list
<T> void applyFunctionToArrayList(ArrayList<T> list, Function<T> func){
    // iterate over the list
    for(T item : list){
        // invoke the "arbitrary" function
        func.Func(item);
    }
}

It's ambiguous in the question, but this might mean returning a new ArrayList, so this might be another acceptable answer

// define the interface to represent an arbitrary function
interface Function<T> {
    T Func(T el);
}

// now the method to apply an arbitrary function to the list
<T> ArrayList<T> applyFunctionToArrayList(ArrayList<T> list, Function<T> func){
    ArrayList<T> newList = new ArrayList<T>();

    // iterate over the list
    for(T item : list){
        // invoke the "arbitrary" function
        newList.add(func.Func(item));
    }
}

On a side note, you would then, say, invoke the application like (for example, doubling every number in the list):

ArrayList<Double> list = Arrays.asList(1.0, 2.0, 3.0);
ArrayList<Double> doubledList = applyFunctionToArrayList(list, 
  new Function<Double>{
    Double Func(Double x){
        return x * 2;
    }
});

Upvotes: 2

Related Questions