动态代理改变 set map 原有的功能

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

 

转载于:https://www.cnblogs.com/qibin/p/3142582.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值