Java Reference
In-Depth Information
}
B.
When it comes to parsing a string into tokens, many programmers' thoughts turn immediately
to
StringTokenizer
. This is most unfortunate, as
StringTokenizer
became obsolete as of
release 1.4, when regular expressions were added to the platform (
java.util.regex
). If you
tried to solve this puzzle with
StringTokenizer
, you quickly realized that it isn't a very good
fit. With regular expressions, it's a snap. To solve this puzzle in one line, use the convenience
method
String.split
, which takes a regular expression describing the token delimiter. If you
haven't used regular expressions before, they may look a bit cryptic, but they're amazingly
powerful and well worth learning:
static String[] parse(String string) {
return string.split(",\\s*");
}
C.
This is a trick question. You don't even have to write a method. The method is provided for
you in release 5.0 and later releases, and is called
Arrays.deepToString
. If you pass it an
array of object references, it returns a nice string representation. It can deal with nested arrays
and even circular references, where an array element refers to the enclosing array, directly or
indirectly. In fact, the
Arrays
class in release 5.0 provides a whole family of
toString
,
equals
, and
hashCode
methods that allow you to print, compare, or hash the contents of any
array of primitives or object references.
D.
In order to solve this puzzle in one line, you need to know that a whole family of
bit-twiddling
methods were added to the platform in release 5.0. The wrapper classes for the integral types
(
Integer
,
Long
,
Short
,
Byte
, and
Char
) now support common bit-manipulation operations,
including
highestOneBit
,
lowestOneBit
,
numberOfLeadingZeros
,
numberOfTrailingZeros
,
bitCount
,
rotateLeft
,
rotateRight
,
reverse
,
signum
, and
reverseBytes
. In this case, what
you need is
Integer.bitCount
, which returns the number of set bits in an
int
value:
static boolean hasMoreBitsSet(int i, int j) {
return (Integer.bitCount(i) > Integer.bitCount(j));
}
Search WWH ::
Custom Search