Using an interface to apply method to ArrayList

╄→尐↘猪︶ㄣ 提交于 2020-01-14 03:08:27

问题


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]);
    }
}

回答1:


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;
    }
});


来源:https://stackoverflow.com/questions/5227448/using-an-interface-to-apply-method-to-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!