2121import java .util .Iterator ;
2222import java .util .NoSuchElementException ;
2323import java .util .Objects ;
24+ import java .util .stream .Collectors ;
2425
2526import opennlp .tools .util .jvm .StringInterners ;
2627
@@ -33,6 +34,9 @@ public class StringList implements Iterable<String> {
3334
3435 private final boolean caseSensitive ;
3536
37+ // It is safe to use caching of the hashCode for this class
38+ private transient Integer hashCode = null ; // initial value is uncomputed
39+
3640 /**
3741 * Initializes a {@link StringList} instance. By default, this instance is case-sensitive.
3842 * <p>
@@ -53,7 +57,7 @@ public StringList(String singleToken) {
5357 *
5458 * @param tokens The string parts of the new {@link StringList}.
5559 * Must not be an empty tokens array or {@code null}.
56- *
60+ *
5761 * @throws IllegalArgumentException Thrown if parameters were invalid.
5862 */
5963 public StringList (String ... tokens ) {
@@ -73,15 +77,13 @@ public StringList(String... tokens) {
7377 * @throws IllegalArgumentException Thrown if parameters were invalid.
7478 */
7579 public StringList (boolean isCaseSensitive , String ... tokens ) {
76-
7780 Objects .requireNonNull (tokens , "tokens must not be null" );
7881
7982 if (tokens .length == 0 ) {
8083 throw new IllegalArgumentException ("tokens must not be empty" );
8184 }
8285
8386 this .tokens = new String [tokens .length ];
84-
8587 for (int i = 0 ; i < tokens .length ; i ++) {
8688 this .tokens [i ] = StringInterners .intern (tokens [i ]);
8789 }
@@ -161,8 +163,11 @@ public boolean compareToIgnoreCase(StringList tokens) {
161163
162164 @ Override
163165 public int hashCode () {
164- // if lookup is too slow optimize this
165- return StringUtil .toLowerCase (toString ()).hashCode ();
166+ if (hashCode == null ) {
167+ // compute once and cache to safe CPU cycles during use
168+ this .hashCode = StringUtil .toLowerCase (String .join ("," , tokens )).hashCode ();
169+ }
170+ return hashCode ;
166171 }
167172
168173 @ Override
@@ -184,21 +189,7 @@ public boolean equals(Object obj) {
184189 */
185190 @ Override
186191 public String toString () {
187- StringBuilder string = new StringBuilder ();
188-
189- string .append ('[' );
190-
191- for (int i = 0 ; i < size (); i ++) {
192- string .append (getToken (i ));
193-
194- if (i < size () - 1 ) {
195- string .append (',' );
196- }
197- }
198-
199- string .append (']' );
200-
201- return string .toString ();
192+ return Arrays .stream (tokens ).collect (Collectors .joining ("," , "[" , "]" ));
202193 }
203194
204195 /**
0 commit comments