使用比较器,我如何确定对象之间的匹配质量,或者有更好的方法

我有一个代码库,我试图在其中确定所提供服务之间的相似性。这些服务有类别。但是,我想通过比较类别集、提供服务所需的时间以及服务成本来确定相似性。我已经编写了代码,它按预期工作(我认为),但我觉得我错过了一些东西,所以我想把它放在这里以获得一些反馈,并获得一些理解。

我假设顺序是(根据类别的相似程度判断):1400、1500、800,然后是 1800。但是,实际顺序是:800、1400、1500、1800。我是比较器的新手,我不是当然我这样做是对的。是否有我遗漏的东西或者这是否正常工作,这是我的假设不正确?我知道我正在尝试使用 3 个不同的道具来确定对象匹配的质量,因此类别的相似程度并不能保证我上面提到的顺序,除非它具有更大的权重。从业务逻辑的角度来看,我认为这没有必要。我只是比较器的新手,并试图理解这一点。感谢您提前提供任何帮助!


潇潇雨雨
浏览 145回答 1
1回答

慕桂英4014372

您正在寻找相似之处。如果比较两个元素的结果为 0,则这些元素是相同的。否则他们不是。我改变了你的日常:public int compare(ProjectService o1, ProjectService o2) {&nbsp; &nbsp; Set<Category> o1CategorySet = o1.getCategories();&nbsp; &nbsp; Set<Category> o2CategorySet = o2.getCategories();&nbsp; &nbsp; int categoryMatch = 0;&nbsp; &nbsp; double matchQuality = 0.0;&nbsp; &nbsp; if ((o1CategorySet != null) && (o2CategorySet != null)) {&nbsp; &nbsp; &nbsp; &nbsp; for (Category o1Category : o1CategorySet) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (Category o2Category : o2CategorySet) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int match = o1Category.getName().compareTo(o2Category.getName());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (match == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; categoryMatch++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; categoryMatch--;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if (categoryMatch == 0) {&nbsp; &nbsp; &nbsp; &nbsp; matchQuality++;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; matchQuality--;&nbsp; &nbsp; }&nbsp; &nbsp; int scaleMatch = o1.getDifficultyScale().getEstimation().compareTo(o2.getDifficultyScale().getEstimation());&nbsp; &nbsp; if (scaleMatch == 0) {&nbsp; &nbsp; &nbsp; &nbsp; matchQuality++;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; matchQuality--;&nbsp; &nbsp; }&nbsp; &nbsp; int amountMatch = o1.getAmount().compareTo(o2.getAmount());&nbsp; &nbsp; if (amountMatch == 0) {&nbsp; &nbsp; &nbsp; &nbsp; matchQuality++;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; matchQuality--;&nbsp; &nbsp; }&nbsp; &nbsp; return (int) matchQuality;}这样排序应该可以正常工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java