001package jmri.jmrix.roco.z21; 002 003import java.util.Comparator; 004import java.util.Objects; 005 006/** 007 * implements a comparator for Z21 CAN bus system names, which include a 008 * hex string for the node address. 009 * 010 * @author Paul Bender Copyright (C) 2019 011 */ 012public class Z21SystemNameComparator implements Comparator<String> { 013 014 private String prefix; 015 private char typeLetter; 016 017 Z21SystemNameComparator(String prefix, char typeLetter){ 018 this.prefix= prefix; 019 this.typeLetter = typeLetter; 020 } 021 022 @Override 023 public int compare(String o1, String o2) { 024 if(o1.equals(o2)){ 025 return 0; 026 } 027 if(o1.startsWith(prefix) && o2.startsWith(prefix) && 028 o1.charAt(prefix.length()) == typeLetter && 029 o2.charAt(prefix.length()) == typeLetter ){ 030 if(o1.contains(":")){ 031 return compareNodePinFormat(o1,o2); 032 } 033 return o1.substring(prefix.length()+1). 034 compareTo(o2.substring(prefix.length()+1)); 035 } 036 return -1; 037 } 038 039 040 private int compareNodePinFormat(String o1,String o2){ 041 if (o1.indexOf(':') == o2.indexOf(':')) { 042 int startIndex = prefix.length() + 1; 043 int stopIndex = o1.indexOf(':'); 044 if (0 == o1.substring(startIndex, stopIndex). 045 compareToIgnoreCase(o2.substring(startIndex, stopIndex))) { 046 return o1.substring(stopIndex). 047 compareToIgnoreCase(o2.substring(stopIndex)); 048 } 049 } 050 return -1; 051 } 052 053 @Override 054 public boolean equals(Object obj) { 055 if (obj == null) { 056 return false; 057 } 058 if (!(obj instanceof Z21SystemNameComparator)){ 059 return false; 060 } 061 Z21SystemNameComparator o = (Z21SystemNameComparator)obj; 062 return this.prefix.equals(o.prefix) && this.typeLetter==o.typeLetter; 063 } 064 065 @Override 066 public int hashCode() { 067 return Objects.hash(prefix,String.valueOf(typeLetter)); 068 } 069 070}