001 // License: GPL. For details, see LICENSE file.
002 package org.openstreetmap.josm.data.osm;
003
004 /**
005 * Tag represents an immutable key/value-pair. Both the key and the value may
006 * be empty, but not null.
007 *
008 */
009 public class Tag {
010
011 private String key;
012 private String value;
013
014 /**
015 * Create an empty tag whose key and value are empty.
016 */
017 public Tag(){
018 this("", "");
019 }
020
021 /**
022 * Create a tag whose key is <code>key</code> and whose value is
023 * empty.
024 *
025 * @param key the key. If null, it is set to the empty key.
026 */
027 public Tag(String key) {
028 this(key, "");
029 }
030
031 /**
032 * Creates a tag for a key and a value. If key and/or value are null,
033 * the empty value "" is assumed.
034 *
035 * @param key the key
036 * @param value the value
037 */
038 public Tag(String key, String value) {
039 this.key = key == null ? "" : key;
040 this.value = value == null ? "" : value;
041 }
042
043 /**
044 * Creates clone of the tag <code>tag</code>.
045 *
046 * @param tag the tag.
047 */
048 public Tag(Tag tag) {
049 this(tag.getKey(), tag.getValue());
050 }
051
052 /**
053 * Replies the key of the tag. This is never null.
054 *
055 * @return the key of the tag
056 */
057 public String getKey() {
058 return key;
059 }
060
061 /**
062 * Replies the value of the tag. This is never null.
063 *
064 * @return the value of the tag
065 */
066 public String getValue() {
067 return value;
068 }
069
070 /**
071 * Replies true if the key of this tag is equal to <code>key</code>.
072 * If <code>key</code> is null, assumes the empty key.
073 *
074 * @param key the key
075 * @return true if the key of this tag is equal to <code>key</code>
076 */
077 public boolean matchesKey(String key) {
078 return this.key.equals(key);
079 }
080
081 @Override
082 public int hashCode() {
083 final int prime = 31;
084 int result = 1;
085 result = prime * result + key.hashCode();
086 result = prime * result + value.hashCode();
087 return result;
088 }
089
090 @Override
091 public boolean equals(Object obj) {
092 if (obj instanceof Tag) {
093 Tag other = (Tag) obj;
094 return key.equals(other.getKey()) && value.equals(other.getValue());
095 } else
096 return false;
097 }
098
099 @Override
100 public String toString() {
101 return key + "=" + value;
102 }
103 }