Java中的Set和SortedSet接口之间的逻辑不一致 [英] logical inconsistence between Set and SortedSet interfaces in Java

查看:149
本文介绍了Java中的Set和SortedSet接口之间的逻辑不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到Java中的Set和SortedSet接口之间的逻辑不一致。



SortedSet在比较期间识别不同对象(通过equal()方法)为等于,如果它们在比较期间相同,但是逻辑上不正确。比较对象只应该对对象的顺序负责。



例如:我可以有很多产品,我想按价格排序。在这种情况下,SortedSet不能包含具有相同价格的不同产品:
[salt,0.5 $],[milk,1 $],[bread,1 $] ,2 $]
在上面的示例中,牛奶将被面包替代。在这种情况下,继承的Set接口的契约将被违反,因为不相等的对象相互替换。我红了SortedSet的JavaDoc,并且知道这个行为记录良好,但我认为这是一个逻辑失败。



你的意见是什么,也许你已经有类似的问题Set和SortedSet?

解决方案

这不是一个逻辑失败,注意如果你的比较算法与equals一致, a.compareTo(b)== 0 将等价于 a.equals(b)



javadoc 其实是非常明确的:


如果其排序与equals不一致;

这很有用吗?



这实际上提供了灵活性,在那里你想达到一个特定的行为。让我们举个例子,你想把字符串放在你的SortedSet中并让它们排序忽略大小写,你可以使用:

  ; String> set = new TreeSet<> (String.CASE_INSENSITIVE_ORDER); 

这将实现预期的结果,但是:

  set.add(ABC); 
set.add(abc);

只会向您的集合添加一个字符串,因为它们将被视为与该特定比较器相同。 p>

I noticed a logical inconsistence between Set and SortedSet interfaces in Java.

SortedSet recognizes different objects (by equal() method) as equals if they are the same during the comparison, but it is logically incorrect. Comparing of objects should be responsible only for order of objects.

For example: I can have many products and I want to sort them by price. In this case the SortedSet can’t contain different products with the same price: ["salt",0.5$], ["milk", 1$], ["bread", 1$], ["bananas", 2$] In example above milk will be replaced by bread. In this case the contract of inherited Set interface will be violated, because unequals objects replace each other. I red JavaDoc of SortedSet and know that this behavior well documented, but I think it is a logical failure.

What is your opinion, maybe you have already similar problems with Set and SortedSet?

解决方案

It is not a logical failure but a property by design. Note that if your comparison algorithm is consistent with equals, a.compareTo(b) == 0 will be equivalent to a.equals(b).

The javadoc is actually very explicit about it:

The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Is that useful?

That actually gives flexibility where you want to reach a specific behaviour. Let's say for example that you want to put strings in your SortedSet and have them sorted ignoring the case, you can use:

Set<String> set = new TreeSet<> (String.CASE_INSENSITIVE_ORDER);

That will achieve the expected result, but this:

set.add("ABC");
set.add("abc");

will only add one string to your set because they will be deemed equal with that specific comparator.

这篇关于Java中的Set和SortedSet接口之间的逻辑不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆