/*******************************************************************************
* Companion code for the book "Introduction to Software Design with Java",
* 2nd edition by Martin P. Robillard.
*
* Copyright (C) 2022 by Martin P. Robillard
*
* This code is licensed under a Creative Commons
* Attribution-NonCommercial-NoDerivatives 4.0 International License.
*
* See http://creativecommons.org/licenses/by-nc-nd/4.0/
*
*******************************************************************************/
package e2.chapter8;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* This source code file shows how to use generic types
* to apply the Visitor pattern so that data flow is accomplished
* via parameters and return types, as opposed to state accumulation
* within the visitor. This is a simplified version of the CardSource
* sample referenced in the chapter.
*/
public class GenericVisitorSample {
public static void main(String[] args) {
GenericCardSource root = new GenericCompositeCardSource(
new GenericDeck(),
new GenericCompositeCardSource(
new GenericDeck(),
new GenericCompositeCardSource(new GenericDeck()),
new GenericDeck()
),
new GenericDeck()
);
// There are five decks in the structure and 5 gets returned and printed
System.out.println(root.accept(new DeckCountingVisitor()));
}
}
interface GenericCardSourceVisitor<R> {
R visitCompositeCardSource(GenericCompositeCardSource pCardSource);
R visitDeck(GenericDeck pCardSource);
}
interface GenericCardSource
{
Card draw();
boolean isEmpty();
<R> R accept(GenericCardSourceVisitor<R> pVisitor);
}
/**
* Stub composite class to demonstrate the implementation of the accept method.
*/
class GenericCompositeCardSource implements GenericCardSource, Iterable<GenericCardSource>
{
private final List<GenericCardSource> aElements;
public GenericCompositeCardSource(GenericCardSource... pCardSources) {
aElements = Arrays.asList(pCardSources);
}
@Override
public Card draw() { /* stub */ return null; }
@Override
public boolean isEmpty() { /* stub */ return false; }
@Override
public <R> R accept(GenericCardSourceVisitor<R> pVisitor) {
return pVisitor.visitCompositeCardSource(this);
}
@Override
public Iterator<GenericCardSource> iterator() {
return aElements.iterator();
}
}
/**
* Stub leaf class to demonstrate the implementation of the accept method.
*/
class GenericDeck implements GenericCardSource
{
@Override
public Card draw() { /* stub */ return null; }
@Override
public boolean isEmpty() { /* stub */ return false; }
@Override
public <R> R accept(GenericCardSourceVisitor<R> pVisitor) {
return pVisitor.visitDeck(this);
}
}
/** Demonstrates how to invoke the generic type to an Integer to return the
* number of deck objects in the structure.
*/
class DeckCountingVisitor implements GenericCardSourceVisitor<Integer> {
@Override
public Integer visitCompositeCardSource(GenericCompositeCardSource pCardSource) {
int result = 0;
for( GenericCardSource source : pCardSource ) {
result += source.accept(this);
}
return result;
}
@Override
public Integer visitDeck(GenericDeck pCardSource) {
return 1;
}
}
Integer class wraps a value of the primitive type
int in an object. An object of type Integer
contains a single field whose type is int.
Integer class wraps a value of the primitive type
int in an object. An object of type Integer
contains a single field whose type is int.
In addition, this class provides several methods for converting
an int to a String and a String to an
int, as well as other constants and methods useful when
dealing with an int.
This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.
Implementation note: The implementations of the "bit twiddling"
methods (such as highestOneBit and
numberOfTrailingZeros) are
based on material from Henry S. Warren, Jr.'s Hacker's
Delight, (Addison Wesley, 2002).
print(String) and then
println().print(String) and then
println().x - The Object to be printed.for statement (sometimes called the "for-each loop" statement).for statement (sometimes called the "for-each loop" statement).for statementSerializable and implements RandomAccess.
Serializable and implements RandomAccess.
The returned list implements the optional Collection methods, except
those that would change the size of the returned list. Those methods leave
the list unchanged and throw UnsupportedOperationException.
Collection.toArray().
This method provides a way to wrap an existing array:
Integer[] numbers = ...
...
List<Integer> values = Arrays.asList(numbers);
This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
The list returned by this method is modifiable.
To create an unmodifiable list, use
Collections.unmodifiableList
or Unmodifiable Lists.
T - the class of the objects in the arraya - the array by which the list will be backedNullPointerException - if the specified array is nullThe methods in this class all throw a NullPointerException,
if the specified array reference is null, except where noted.
The documentation for the methods contained in this class includes
brief descriptions of the implementations. Such descriptions should
be regarded as implementation notes, rather than parts of the
specification. Implementors should feel free to substitute other
algorithms, so long as the specification itself is adhered to. (For
example, the algorithm used by sort(Object[]) does not have to be
a MergeSort, but it does have to be stable.)
This class is a member of the Java Collections Framework.
Unlike sets, lists typically allow duplicate elements. More formally,
lists typically allow pairs of elements e1 and e2
such that e1.equals(e2), and they typically allow multiple
null elements if they allow null elements at all. It is not inconceivable
that someone might wish to implement a list that prohibits duplicates, by
throwing runtime exceptions when the user attempts to insert them, but we
expect this usage to be rare.
The List interface places additional stipulations, beyond those
specified in the Collection interface, on the contracts of the
iterator, add, remove, equals, and
hashCode methods. Declarations for other inherited methods are
also included here for convenience.
The List interface provides four methods for positional (indexed)
access to list elements. Lists (like Java arrays) are zero based. Note
that these operations may execute in time proportional to the index value
for some implementations (the LinkedList class, for
example). Thus, iterating over the elements in a list is typically
preferable to indexing through it if the caller does not know the
implementation.
The List interface provides a special iterator, called a
ListIterator, that allows element insertion and replacement, and
bidirectional access in addition to the normal operations that the
Iterator interface provides. A method is provided to obtain a
list iterator that starts at a specified position in the list.
The List interface provides two methods to search for a specified
object. From a performance standpoint, these methods should be used with
caution. In many implementations they will perform costly linear
searches.
The List interface provides two methods to efficiently insert and
remove multiple elements at an arbitrary point in the list.
Note: While it is permissible for lists to contain themselves as elements,
extreme caution is advised: the equals and hashCode
methods are no longer well defined on such a list.
Some list implementations have restrictions on the elements that
they may contain. For example, some implementations prohibit null elements,
and some have restrictions on the types of their elements. Attempting to
add an ineligible element throws an unchecked exception, typically
NullPointerException or ClassCastException. Attempting
to query the presence of an ineligible element may throw an exception,
or it may simply return false; some implementations will exhibit the former
behavior and some will exhibit the latter. More generally, attempting an
operation on an ineligible element whose completion would not result in
the insertion of an ineligible element into the list may throw an
exception or it may succeed, at the option of the implementation.
Such exceptions are marked as "optional" in the specification for this
interface.
The List.of and
List.copyOf static factory methods
provide a convenient way to create unmodifiable lists. The List
instances created by these methods have the following characteristics:
UnsupportedOperationException to be thrown.
However, if the contained elements are themselves mutable,
this may cause the List's contents to appear to change.
null elements. Attempts to create them with
null elements result in NullPointerException.
subList views implement the
RandomAccess interface.
This interface is a member of the Java Collections Framework.
Iterator takes the place of
Enumeration in the Java Collections Framework. Iterators
differ from enumerations in two ways:
Iterator takes the place of
Enumeration in the Java Collections Framework. Iterators
differ from enumerations in two ways:
This interface is a member of the Java Collections Framework.
Enumeration can be converted into an Iterator by
using the Enumeration.asIterator() method.String class represents character strings. All
string literals in Java programs, such as "abc", are
implemented as instances of this class.
String class represents character strings. All
string literals in Java programs, such as "abc", are
implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2, 3);
String d = cde.substring(1, 2);
The class String includes methods for examining
individual characters of the sequence, for comparing strings, for
searching strings, for extracting substrings, and for creating a
copy of a string with all characters translated to uppercase or to
lowercase. Case mapping is based on the Unicode Standard version
specified by the Character class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null argument to a constructor
or method in this class will cause a NullPointerException to be
thrown.
A String represents a string in the UTF-16 format
in which supplementary characters are represented by surrogate
pairs (see the section Unicode
Character Representations in the Character class for
more information).
Index values refer to char code units, so a supplementary
character uses two positions in a String.
The String class provides methods for dealing with
Unicode code points (i.e., characters), in addition to those for
dealing with Unicode code units (i.e., char values).
Unless otherwise noted, methods for comparing Strings do not take locale
into account. The Collator class provides methods for
finer-grain, locale-sensitive String comparison.
javac compiler
may implement the operator with StringBuffer, StringBuilder,
or java.lang.invoke.StringConcatFactory depending on the JDK version. The
implementation of string conversion is typically through the method toString,
defined by Object and inherited by all classes in Java.Console.charset() if the Console exists,
stdout.encoding otherwise.
Console.charset() if the Console exists,
stdout.encoding otherwise.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println methods in class PrintStream.
System class contains several useful class fields
and methods. It cannot be instantiated.
Among the facilities provided by the System class
are standard input, standard output, and error output streams;
access to externally defined properties and environment
variables; a means of loading files and libraries; and a utility
method for quickly copying a portion of an array.System class contains several useful class fields
and methods. It cannot be instantiated.
Among the facilities provided by the System class
are standard input, standard output, and error output streams;
access to externally defined properties and environment
variables; a means of loading files and libraries; and a utility
method for quickly copying a portion of an array.