1.首先自定義一個Operate接口,以下所示:java
public interface Operate { public Integer caozuo(Integer i); }
2.實現自定義的ArrayList類,即自定義MyArrayList類,以下:ide
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接口的類,可是咱們這裏可使用匿名接口實現類,因此測試代碼以下:測試
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); } }