SET 功能 根据其中对象的name 属性 去重
final Set<User> users = new HashSet<User>();
Set<User> set = (Set<User>)Proxy.newProxyInstance( HashSet.class.getClassLoader(), HashSet.class.getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().endsWith("add") && null!=args ) { User user6=(User) args[0]; for(User user : users){ if(user.getName().equals(user6.getName())){ return false; } } return method.invoke(users,args); } else { return method.invoke(users,args); } } }); User user = new User(); user.setName("4444"); User user2 = new User(); user2.setName("4444"); set.clear(); set.add(user); set.add(user2); for(User user3: users){ System.out.println(user3.getName().toString()); }
map集合 具备功能: KEY 相同的 VALUE 叠加
final Map<String,Integer> tabMap = new HashMap<String,Integer>(); ; Map<String,Integer> tabMapPoxy = (Map<String,Integer>)Proxy.newProxyInstance( HashMap.class.getClassLoader(), HashMap.class.getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().endsWith("put") && null!=args ) { // 这里判断 if(tabMap.keySet().contains(args[0])){ Integer oldValue = tabMap.get(args[0]); Integer newValue = oldValue+(Integer)args[1]; tabMap.put((String)args[0], newValue); return false; }else{ return method.invoke(tabMap,args); } } else { return method.invoke(tabMap,args); } } }); tabMapPoxy.put("111", 2); tabMapPoxy.put("111", 2); tabMapPoxy.put("111", 2); tabMapPoxy.put("111", 0); tabMapPoxy.put("222", 3); tabMapPoxy.put("222", 3); tabMapPoxy.put("222", 3); for(String key: tabMap.keySet()){ System.out.println(key+"===="+tabMap.get(key)); }