Jump to content

Java Version

From EggeWiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

A frequent computer science problem is comparing version numbers. Version numbers are like decimal numbers with multiple decimal points. One can not accurately compare version numbers as a string or a number. Often you want to see if a version is later than another version. Here's a Java class which goes about solving this problem.

<geshi lang="java"> public class Version implements Comparable, Serializable { private final int version[];

public Version(String version) { String[] split = version.split("\\."); this.version = new int[split.length]; for (int i = 0; i < split.length; i++) { String string = split[i]; this.version[i] = Integer.valueOf(string).intValue(); } } private static final long serialVersionUID = 5028475470314950450L;

public int compareTo(Object o) { if (this == o) return 0; final int[] other = ((Version) o).version; int length = Math.max(version.length, other.length); for(int i = 0; i < length; i++) { int x = (i < version.length) ? version[i] : 0; int y = (i < other.length) ? other[i] : 0; if (x < y) return -1; if (x > y) return 1; } return 0; }

public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Version.hashCode(version); return result; }

public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Version other = (Version) obj; if (!Arrays.equals(version, other.version)) return false; return true; }

private static int hashCode(int[] array) { final int prime = 31; if (array == null) return 0; int result = 1; for (int index = 0; index < array.length; index++) { result = prime * result + array[index]; } return result; }

public String toString() { String s = ""; for (int i = 0; i < version.length; i++) { if (!"".equals(s)) s += "."; s += Integer.toString(version[i]); } return s; }

} </geshi>