java - 使用接口(interface)将方法应用于 ArrayList

标签 java loops arraylist

我正在复习考试。旧测试的一个问题是:使用接口(interface),编写一个方法,将任意方法应用于 ArrayList 的每个元素。 arraylist 和方法都是方法的参数。

可行的解决方案是:

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,因此这可能是另一个可接受的答案

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

顺便说一句,您可以像这样调用应用程序(例如,将列表中的每个数字加倍):

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

关于java - 使用接口(interface)将方法应用于 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5227448/

相关文章:

javascript - While 循环增加数字直到高于或等于目标

Python - 返回一个 break 语句

java - 将数组列表从一个 Activity 发送到另一个 Activity 到 ListView android中

java - 我如何使用 BlobstoreService java 下载谷歌云存储中的文件

java - 使用流 groupingBy 时将字符串分组为多个组

python - Python 3.4 中可以选择迭代器的起点吗?

java - 修改 getter 的结果会影响对象本身吗?

java - 无法对我的字符串 ArrayList 进行排序

android - 库的 java.lang.NoClassDefFoundError 异常

java - Java "public static void main(string[] args)"是创建 main 方法的唯一方法吗?