/* An instance of this class represents a (key,value)-pair in which ** both key and value components are of type String. ** Such pairs exist to correlate codes, abbreviations, etc., with ** their corresponding full elaborations. ** ** As an example, consider that each of the states in the U.S. has a ** two-character postal key abbreviation. Thus, in the familiar pair ** ("PA","Pennsylvania"), the first component is the key and the second is ** the corresponding value. Similarly for ("NY", "New York"), etc. ** ** Author: P.M.J., R.W.M. ** last modified: 12/06/2025 */ public class KeyValPair { // instance variables (fields/attributes) // -------------------------------------- protected String key = ""; // protected String value = ""; // protected static final String DELIMITER = ":"; // constructors // ------------ /* Initilizes this KeyValPair object to have the empty string ** as both its key and its value/elaboration. */ public KeyValPair() {} /* Initializes this KeyValPair object to have the given ** strings as its two components (key and value). */ public KeyValPair(String key, String value) { setTo(key,value); } /* Initializes this KeyValPair object to be that described by ** the given string, which is expected to be in the form ** ** key : value ** ** consistent with the form produced by the toString() method. ** If the given string is not consistent with that format, both ** components of this KeyValPair object will be the empty string. */ public KeyValPair(String fromString) { setTo("",""); //Set default values //Separate the string into its two required parts int posOfDelimiter = fromString.indexOf(DELIMITER); if (posOfDelimiter != -1) { // What precedes the occurrence of the delimiter is the key, // and what follows it is the associated value/elaboration. this.key = fromString.substring(0, posOfDelimiter).trim(); this.value = fromString.substring(posOfDelimiter + DELIMITER.length()).trim(); } } // observers // --------- /* Returns the key component of this KeyValPair object. */ public String getKey() { return this.key; } /* Returns the value component of this KeyValPair object. */ public String getValue() { return this.value; } /* Returns true if and only if the given string matches ** the key component of this KeyValPair object. */ public boolean equalsKey(String key) { return key.equals(this.getKey()); } /* Returns true if and only if the given string matches ** the value component of this KeyValPair object. */ public boolean equalsValue(String value) { return value.equals(this.getValue()); } /* Returns a string of the following form that represents ** the current state and value of this KeyValPair object. ** ** key : value */ @Override public String toString() { return key + DELIMITER + value; } // private mutator // --------------- /* Makes this KeyValPair object have as its two components ** the specified pair of strings. */ protected void setTo(String key, String value) { this.key = key; this.value = value; } }