Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 8ca7c564a29979f84607dff6cab74bc03db2ea67 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*******************************************************************************
 * Copyright (c) 2011 Red Hat, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Red Hat Incorporated - initial API and implementation
 *******************************************************************************/

package org.eclipse.cdt.internal.autotools.core;

public class VersionComparator {

	/**
	 * Compare two version numbers if
	 * return -1 if v1 is older than v2 0 if they are the same and +1
	 * if v1 is newer than v2
	 * 
	 * Version numbers are expected to be in the format x.y.z...
	 * 
	 * So:
	 * 	VersionComparator.compare("1.0", "1.2") return -1
	 *  VersionComparator.compare("1.5", "1.2") returns 1
	 *  VersionComparator.compare("1.5.1", "1.5.5") returns -1
	 *  VersionComparator.compare("1.5", "1.5.1")  returns 1
	 *  VersionComparator.compare("1.5.1", "1.5.1")  returns 0
	 */
	public static int compare(String v1, String v2) {
		String[] v1digits = v1.split("\\.");
		String[] v2digits = v2.split("\\.");
		
		for (int i = 0; i < v1digits.length && i < v2digits.length; i++) {
			int d1 = Integer.valueOf(v1digits[i]);
			int d2 = Integer.valueOf(v2digits[i]);
			
			if (d1 < d2)
				return -1;
			
			if (d1 > d2)
				return 1;
		}
		
		// At this point all digits have the same value
		// so the version with the longer string wins
		
		if (v1digits.length < v2digits.length)
			return -1;
		
		if (v1digits.length > v2digits.length)
			return 1;

		return 0;
	}
	
}

Back to the top