使用接口将方法应用于 ArrayList [英] Using an interface to apply method to ArrayList
本文介绍了使用接口将方法应用于 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在复习考试.旧测试中的一个问题是:使用接口编写一个方法,该方法将任意方法应用于 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.
可行的解决方案是:
public <object> someMethod() {
scanner GLaDOS = new (someArray);
someArray.useDelimiter(",");
for (i = 0; i < someArray.length; i++) {
someOtherMethod(someArray[i]);
}
}
推荐答案
我会期待这样的:
// 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);
}
}
<小时>
问题含糊不清,但这可能意味着返回一个新的 ArrayList,因此这可能是另一个可接受的答案
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;
}
});
这篇关于使用接口将方法应用于 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文