1.首先自定义一个Operate接口,如下所示:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public interface Operate { public Integer caozuo(Integer i); }
2.实现自定义的ArrayList类,即自定义MyArrayList类,如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import java.util.ArrayList; public class MyArrayList { private ArrayList<Integer> list; private ArrayList<Integer> resultList; public MyArrayList(ArrayList<Integer> list) { this.list = list; } public ArrayList<Integer> map(Operate op){ resultList = new ArrayList<Integer>(); for(Integer i : list){ resultList.add(op.caozuo(i)); } return resultList; } }
3.按正说还需要写一个实现Operate接口的类,但是我们这里可以使用匿名接口实现类,所以测试代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import java.util.ArrayList; public class Test01 { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); MyArrayList myList = new MyArrayList(list); ArrayList<Integer> map = myList.map(new Operate() { @Override public Integer caozuo(Integer i) { return i * 10; } }); System.out.println(map); } }