Java tutorial
/* * The MIT License * * Copyright 2015 Marko Zivanovic <marko@zivanovic.in.rs>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package rs.in.zivanovic.jdepmon.core; import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; import java.util.Comparator; import java.util.List; /** * Compare two version strings. Version strings are split into components and each components is compared as number, if * it can be parsed as such, or as a string otherwise. If all components up to the length of the shorter version string * are equal, shorter version has precedence. */ public class VersionComparator implements Comparator<String> { private static final String SEPARATORS = ".-+"; @Override public int compare(String o1, String o2) { List<String> comps1 = Splitter.on(CharMatcher.anyOf(SEPARATORS)).splitToList(o1); List<String> comps2 = Splitter.on(CharMatcher.anyOf(SEPARATORS)).splitToList(o2); int res = 0; int ssize = comps1.size() >= comps2.size() ? comps2.size() : comps1.size(); int i = 0; Comparable comp1, comp2; while (i < ssize) { try { comp1 = Long.parseLong(comps1.get(i)); comp2 = Long.parseLong(comps2.get(i)); } catch (NumberFormatException ex) { comp1 = comps1.get(i).toLowerCase(); comp2 = comps2.get(i).toLowerCase(); } res = comp1.compareTo(comp2); if (res != 0) { break; } i = i + 1; } if (res == 0 && comps1.size() != comps2.size()) { res = comps1.size() > comps2.size() ? -1 : 1; } return res; } }