Using an interface to apply a method to an ArrayList
I am reviewing the exam. The old test question was this: Using an interface, write a method that applies an arbitrary method to each element of the ArrayList. Parameter and method are method parameters.
Will a workable solution be:
public <object> someMethod() {
scanner GLaDOS = new (someArray);
someArray.useDelimiter(",");
for (i = 0; i < someArray.length; i++) {
someOtherMethod(someArray[i]);
}
}
+1
source to share
1 answer
I would expect 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);
}
}
This is ambiguous in the question, but it could mean returning a new ArrayList, so this could 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 are, say, invoking the application, for example (like 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;
}
});
+2
source to share