Java Reference
In-Depth Information
When the method runs, the hash is computed by stepping through the array of
characters. At the end of the array, we exit the for loop and write the computed
hash back into the field hash . Now, when this method is called again, the value has
already been computed, and so we can just use the cached value. So subsequent calls
to hashCode() return immediately.
The computation of a string's hash code is an example of a
benign data race . In a program with multiple threads, they
could race to compute the hash code. However, they would all
eventually arrive at exactly the same answer—hence the term
benign .
All of the fields of the String class are final, except for hash . So Java's strings are
not, strictly speaking, immutable. However, because the hash field is just a cache of
a value that is deterministically computed from the other fields, which are all
immutable, then provided String has been coded correctly, it will behave as if it was
immutable. Classes that have this property are called efectively immutable —they are
quite rare in practice, and working programmers can usually ignore the distinction
between truly immutable and effectively immutable data.
Regular Expressions
Java has support for regular expressions (often shortened to regex or regexp ). These
are a representation of a search pattern used to scan and match text. A regex is a
sequence of characters that we want to search for. They can be very simple—for
example, abc means that we're looking for a , followed immediately by b , followed
immediately by c , anywhere within the text we're searching through. Note that a
search pattern may match an input text in zero, one, or more places.
The simplest regexs are just sequences of literal characters, like abc . However, the
language of regexs can express more complex and subtle ideas than just literal
sequences. For example, a regex can represent patterns to match like:
• A numeric digit
• Any letter
• Any number of letters, which must all be in the range a to j but can be upper-
or lowercase
a followed by any four characters, followed by b
The syntax we use to write regular expressions is simple, but because we can build
up complex patterns, it is often possible to write an expression that does not imple‐
ment precisely what we wanted. When using regexs, it is very important to always
test them fully. This should include both test cases that should pass and cases that
should fail.
m
m
n
s
a
 
Search WWH ::




Custom Search