[英]Most concise way of comparing versions in Java
Let's say I have a version of the form of major.minor.patch
, eg 1.2.3
, and I want to compare it to another version 1.1.5
, as 2 > 1
the first version is greater than the second.假设我有一个
major.minor.patch
形式的版本,例如1.2.3
,我想将它与另一个版本1.1.5
进行比较,因为2 > 1
第一个版本大于第二个版本。 How can I write the most concise & efficient compare function for the class Version
:如何为
class Version
编写最简洁、最有效的比较函数:
class Version implements Comparable<Version> {
int major
int minor
int patch
@Override
int compareTo(Version otherVersion) {
// ... TODO
}
}
Answers can be in Java
or Groovy
.答案可以是
Java
或Groovy
。
I would suggest adding getters for your three fields, then a Comparator
using chained comparing functions.我建议为您的三个字段添加 getter,然后使用链式比较函数添加一个
Comparator
。 Like,喜欢,
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getPatch() {
return patch;
}
private static final Comparator<Version> COMP = Comparator
.comparingInt(Version::getMajor)
.thenComparingInt(Version::getMinor)
.thenComparingInt(Version::getPatch);
@Override
public int compareTo(Version otherVersion) {
return COMP.compare(this, otherVersion);
}
groovy variant时髦的变种
@groovy.transform.ToString
class Version implements Comparable<Version> {
int major
int minor
int patch
@Override
int compareTo(Version other) {
major<=>other.major ?: minor<=>other.minor ?: patch<=>other.patch
}
}
def v0=new Version(major:1,minor:2,patch:11)
def v1=new Version(major:1,minor:2,patch:22)
def v2=new Version(major:1,minor:2,patch:33)
assert v1.compareTo(v0)==1
assert v1.compareTo(v2)==-1
assert v1.compareTo(v1)==0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.