1

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]);
    }
}
2
  • Is that the exact question from the test? It's not very clear, IMO. Commented Mar 8, 2011 at 1:53
  • @Andrew, yes that's all it says. Commented Mar 8, 2011 at 1:54

1 Answer 1

2

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;
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Your method could give back a new ArrayList of the results.
@Paŭlo Ebermann: it could but the question asked for application to every array element, I'll update nonetheless.
thanks! This looks good, I'll see if the prof says it's what he was looking for.
I think the Function interface should be interface Function<T, R> { R Func(T el); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.