源码解读两个JSONObject的equals方法

alibaba.fastjson源码分析JSONObject的equals方法

JSONObject的创建

//默认创建一个空的JSONObject 底层使用的是hashMap
//hashMap内部是按照key的ASCII码进行排序
 JSONObject jsonObj1 = new JSONObject();
//创建一个内部有序的JSONObject,那么可以使用linkedHashMap
//指定内部数据按照put的顺序有序排序
 JSONObject jsonObj2 = new JSONObject(true);

两个JSONObject对象的比较

json1.equals(json2)----> 需不需要考虑内部存储的<k,v>的顺序呢??
源码点进去 json的equals内部 调用的是 this.map.euqals(obj)
 public boolean equals(Object obj) {
        return this.map.equals(obj);
    }

map的equals内部调用什么呢???

 /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    boolean equals(Object o);

上面清楚的解释到,调用两个对象的entrySet()的equals方法

那么,一起来看看entrySet()内部的equals方法是怎么写的??

 /**
     * Compares the specified object with this set for equality.  Returns
     * <tt>true</tt> if the specified object is also a set, the two sets
     * have the same size, and every member of the specified set is
     * contained in this set (or equivalently, every member of this set is
     * contained in the specified set).  This definition ensures that the
     * equals method works properly across different implementations of the
     * set interface.
     *
     * @param o object to be compared for equality with this set
     * @return <tt>true</tt> if the specified object is equal to this set
     */
    boolean equals(Object o);

可知,entrySet()的equals方法内部判断依据两点!!!

第一点: 两个set的size,(entrySet的size与传入json内部的key的个数有关)

第二点: set1包含set2的全部元素并且set2包含set1的全部元素 ---->也就是说内部调用的set集合的containsAll方法----> containsAll内部就是通过遍历去判断的!!!

  • 所以说,判断两个JSONObject是否相同,并不需要使得内部key顺序相同。
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值