泛型类与子类型:求PayloadList泛型接口可运行实现示例
PayloadList 接口可运行实现示例
我们可以基于JDK自带的ArrayList扩展实现,ArrayList已经实现了List接口的所有基础方法,只需额外补充payload的存储和读写逻辑即可,完整可运行代码如下:
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; // Oracle官方示例定义的PayloadList接口 interface PayloadList<E,P> extends java.util.List<E> { void setPayload(int index, P val); // 补充getPayload方法方便读取负载数据 P getPayload(int index); } // PayloadList实现类,复用ArrayList的List基础能力 class PayloadArrayList<E,P> extends ArrayList<E> implements PayloadList<E,P> { // 用Map存储索引对应的负载数据 private final Map<Integer, P> payloadMap = new HashMap<>(); @Override public void setPayload(int index, P val) { // 校验索引合法性 if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } payloadMap.put(index, val); } @Override public P getPayload(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size()); } return payloadMap.get(index); } } // 测试类,验证不同参数化类型的使用 public class PayloadListDemo { public static void main(String[] args) { // 测试1:PayloadList<String,String> 类型 System.out.println("=== 测试String-String类型 ==="); PayloadList<String, String> strStrList = new PayloadArrayList<>(); strStrList.add("第一条数据"); strStrList.add("第二条数据"); strStrList.setPayload(0, "第一条的字符串负载"); strStrList.setPayload(1, "第二条的字符串负载"); for (int i = 0; i < strStrList.size(); i++) { System.out.println("元素值:" + strStrList.get(i) + ",负载值:" + strStrList.getPayload(i)); } // 测试2:PayloadList<String,Integer> 类型 System.out.println("\n=== 测试String-Integer类型 ==="); PayloadList<String, Integer> strIntList = new PayloadArrayList<>(); strIntList.add("苹果"); strIntList.add("香蕉"); strIntList.setPayload(0, 15); strIntList.setPayload(1, 8); for (int i = 0; i < strIntList.size(); i++) { System.out.println("元素值:" + strIntList.get(i) + ",负载值:" + strIntList.getPayload(i) + "元/斤"); } // 测试3:PayloadList<String,Exception> 类型 System.out.println("\n=== 测试String-Exception类型 ==="); PayloadList<String, Exception> strExList = new PayloadArrayList<>(); strExList.add("执行任务A"); strExList.add("执行任务B"); strExList.setPayload(1, new RuntimeException("任务B执行失败,网络超时")); for (int i = 0; i < strExList.size(); i++) { System.out.print("任务内容:" + strExList.get(i)); Exception ex = strExList.getPayload(i); if (ex != null) { System.out.println(",异常信息:" + ex.getMessage()); } else { System.out.println(",执行成功无异常"); } } } }
内容的提问来源于stack exchange,提问作者Yauheni
相关产品推荐
相关产品推荐

