• Java 2 Platform Standard Edition 5.0 API specification
• OpenJDK source code repository for library classes
• Source code from Data structures and problem-solving using Java, third edition
(in preparation)
(in preparation)
(in preparation)
(in preparation)
(in preparation)
(in preparation)
hash function is applied to them?
How would you go about finding a large number of strings s such that
hash(s, 100003) has the same value for each?java.lang.String has to override the
hashCode method so that it returns equal hash codes for equal
strings (even if they are stored in different locations). Find out how the
OpenJDK programmers implemented hashCode. Would this be a suitable
basis for a hash function in an implementation of hash tables? What
further operations would one have to perform on the result of hashCode?k of the findKth method is interpreted as a
zero-based index.(in preparation)
(in preparation)
(in preparation)
int variable that counts unmated left parentheses. Start the
counter at 0 and traverse the given string from left to right. Add 1 to
the counter every time you come to a left parenthesis; subtract 1 from it
every time you come to a right parenthesis. The string is correctly nested
and balanced if, and only if, the counter is zero at the end of the
traversal and has never had a negative value at any point along the way.
Revise your code so that it uses this approach.incoming
and outgoing. Both stacks start out empty (representing an empty
queue). To enqueue an item, we push it onto the incoming stack. Whenever
we need to perform any operation involving the front of the queue, we first
check whether the outgoing stack is empty; if it is, we repeatedly pop
elements from the incoming stack and push them onto the outgoing stack,
until the incoming stack is empty. Then we proceed with the operation: To
dequeue an item, we pop it from the outgoing stack, and to inspect an item
without removing it from the queue, we examine the item at the top of the
outgoing stack. The queue is empty if, and only if, both stacks are
empty. Write a Java implementation of queues based on this idea.printList method on page 572 so that it prints
out the contents of the list with an open-bracket at the beginning, a
close-bracket at the end, and a comma and a space between each pair of
adjacent elements. Your procedure should not print an extra space in front
of the close-parenthesis.last method that performs this operation on
a singly-linked list and determine the order of its running-time function.
Why is this unsatisfactory?LinkedList data type (in section
17.5) implements his simplified Queue interface from page 229, but
not the full java.util.Queue interface. How would one have to
change it in order to get it to implement java.util.Queue?ArrayList class that
Weiss provides in Figures 15.13 through 15.16 and then add sixty elements
to it without removing any. How large will the underlying array stored in
the theItems field of the ArrayList be at that point?remove procedure in lines 93 through 101 of Figure 15.14 in the text.ArrayStack class, Weiss uses a topOfStack field
to keep track of the position in the underlying array occupied by the most
recently pushed element of the stack. An alternative design would
eliminate topOfStack in favor of a size field that keeps
track of the number of items currently in the stack. How would you have to
change the implementation of the ArrayStack method to accommodate
this alternate design? (Hint: Examine each reference to the topOfStack field.)java.lang.Math.random(), write a Java
expression for a randomly selected capital letter of the English alphabet.
(Hint: the integer value of the capital letter 'A' is 65 and the
integer value of the capital letter 'Z' is 90.)size
as argument and returns an array containing the integers from 0 up to and
including size - 1, in a random order. (All arrangements of the
integers should be equally probable.)java.util.Random.nextInt() method by using it to
generate 100000 pairs of values and counting how many of them are
even-even, how many are even-odd, how many are odd-even, and how many are
odd-odd. There should be roughly the same number of pairs in each
category, although it would also be suspicious if each group had exactly
25000 pairs.priorityQueueSort method that
takes a second argument, a Comparator for values of some class that
is a superclass of AnyType, and uses that Comparator to
compare elements of the given array when sorting them.priorityQueueSort
is sensitive to the ordering of the original data. Run some tests in which
priorityQueueSort is applied to an array that is already in
ascending order, and some in which it is applied to an array that is
initially in reverse order. Are the running times comparable to each other
and to the method's running times on randomly ordered arrays?ranked, and guarantees only that the
first ranked positions of the resulting array contain the correctly
sorted values (i.e., that they are the ranked smallest values in the
array, in ascending order)?java.util.Arrays.sort1 method
that we looked at in class do if it is asked to sort an array in which all
of the values are equal? What will be the general order of its
running-time function in this case?insertionSort method in Figure 8.2 of our textbook, why
doesn't the evaluation of the expression a[j - 1] through an ArrayIndexOutOfBoundsException when the value of j is 0?insertionSort but also to several other sorting algorithms.
It doesn't apply to the Shell sort, however. Why not?selectionSort
algorithm demonstrated in class?drawRuler method in Figure
7.13 of our textbook, giving level the value 20. What is the
greatest number of activation records for drawRuler calls that will
ever be on the stack simultaneously? Is there any possibility that we'll
run out of space for those activation records?PriorityQueue is constructed, if the class to which its
elements belong doesn't implement the Comparable interface, the
programmer must supply a Comparator object as an argument to the
constructor. Why?TreeSet<String> containing the names of the Iowa
counties that are less densely populated than the state as a whole.equals method should also override
the hashCode method. Why?ArrayList instead of a LinkedList?ArrayList, it doesn't make much
difference whether one writes
for (int index = 0; index < ls.size(); index++)
ls.get(index).doSomething();
or
for (Whatever element : ls)
element.doSomething();
However, when one is traversing a large LinkedList, the second
version can be much, much faster. Why?MyStack class that implements the "stack
protocol" shown in Figure 6.21 of our textbook.Collection interface must
implement the remove method. Yet the objects of some classes that
implement Collection are "immutable" -- their sizes and constants
can't change. How can the remove method operate on an immutable
collection?add method in the Collection interface returns a
Boolean value -- true if the operation succeeds, false if it
does not. Could an add operation on a mutable collection ever fail?
How?main method, let switchBoard be a variable of type
Collection<Switch>, where Switch is the toggle-switch
class that we defined earlier in the semester. Write a
loop that turns off all of the switches in the collection that is the
current value of switchBoard.next method) have the side effect of advancing
the other? Justify your answers.MyContainer and MyContainerIterator classes
and the Iterator interface from section 6.2.2 of the textbook, write
a sequence of Java statements that stores into a BigInteger variable
total the sum of the elements of a MyContainer called seq. You may assume that every element of seq is a BigInteger.MyContainer, MyContainerIterator, and Iterator from
/home/stone/courses/java/examples.setVisible method to make the
window appear on screen?JLabel to display the current value of the counter field in a
tallier. Why is this preferable to using a JTextField?ActionListener with a particular JButton in a graphical user interface?VisibleTallier that we developed in the lab, the
buttons are placed at the top of the interface. What would we change to
place them at the bottom instead?javax.swing) related to the Abstract
Widget Toolkit (java.awt)?JFrame class?ActionListener interface?
public static boolean isAllNulls(Object[] arr) {
for (Object element: arr)
if (element != null)
return false;
return true;
}
What is the order of the function that describes its running time? Is the
"lower bound" order the same as the "upper bound" order?maxSide.)
public static void rightTriangles(int maxSide) {
for (int hypotenuse = 3; hypotenuse <= maxSide; hypotenuse++)
for (int longLeg = 2; longLeg < hypotenuse; longLeg++)
for (int shortLeg = 1; shortLeg < longLeg; shortLeg++)
if (shortLeg * shortLeg + longLeg * longLeg ==
hypotenuse * hypotenuse)
System.out.println(shortLeg + "-" + longLeg + "-" +
hypotenuse);
}
GenericMemoryCell class shown in Figure 4.28 of the
textbook allows us to create a memory cell that will store, say, a Fraction and nothing else, by writing new
GenericMemoryCell<Fraction>, or a Shape and nothing else, by
writing new GenericMemoryCell<Shape>. Suppose, though, that we
want to write a method that takes a memory cell as a parameter, but only if
it is a memory cell that is either specified to hold a Shape or
specified to hold an object of some class that extends Shape. In
defining that method, how would we write the type for the parameter?copyArray that takes two
parameters, each of which must be an array of values of some non-primitive
type, and copies the elements of the first into the second (overwriting the
values previously stored in the second array). The method should check to
make sure that the two arrays have the same length (throwing an exception
if they are not) and should also ensure that the type of the elements of
the source array is the same as, or a subtype of, the type of the elements
of the target array.IntFunction interface containing a single (abstract)
method, operateOn, that takes one int parameter and returns
an int value. Define a SquareFunction class that implements
this interface; it should implement operateOn as a function that
squares its argument. Similarly, define a SuccessorFunction class
that implements operateOn as a function that returns the successor
of its argument. Finally, define a Mapper class, with a method
map that takes two arguments, an IntFunction func and
an array arr of ints, and returns a newly allocated array
containing the results of applying func to each argument of arr in turn. Demonstrate these functions by computing the squares of the
successors of the elements of the array {-7, 12, 0}.RegularHexagon class to the Shape hierarchy
presented in section 4.2 of the textbook, constructing each object of this
class from the length of its side.Triangle class, with a
triangle being specified by the lengths of its sides. Hint: If a, b, and c are the lengths of the sides of a
triangle, and s is its semiperimeter, then its area is the
square root of the product s(s - a)(s - b)(s - c). (Thanks,
Heron of Alexandria!)M extends class K. An object of
class M is then type-compatible with a local variable, field, or
parameter that is declared to be of type K, and can be stored in
such a variable, field, or parameter. Is the converse true? Is an object
of class K type-compatible with with a local variable, field, or
parameter that is declared to be of type M? Justify your answer.M that extends another class K cannot override
any public method of K with a private method that has the same
signature. Why is this not permitted?final. What considerations would affect this
decision? What advantages or disadvantages do final methods have?CoinBox class that you developed in today's lab
a method for releasing a quarter. What should this method do if the CoinBox to which the message is sent contains no quarters?CoinBox can contain
as many as 2147483647 coins of each type. Impose a more realistic limit,
say 480. What should your deposit methods do if the CoinBox
is full and can't receive any more coins?Fraction constructors?Fraction class,
initializing them to the fractions 0/1 and 1/1, respectively.compareTo method to the definition of the Fraction class. It should take one argument, a fraction, and return a
negative int value if the fraction that receives the compareTo message is less than the argument, a positive int value
if the argument is less than the fraction that receives the message, and
the int 0 if the two fractions are equal.pow method to the definition of the Fraction
class. It should take one argument, an int, and return the result
of raising the fraction that receives the pow message to the
specified power. (Consider carefully what should happen if the argument is
zero or negative.)-private command-line argument to
the javadoc program?@param tag in a documentation comment do?Fraction constructor that takes as arguments
strings that represent the intended numerator and denominator.Fraction constructor that takes a single
argument n of type int and constructs the Fraction
n/1.toString message to an object of
the Switch class that we defined in class.
Write a program that prints out the string that is returned as the
representation of a Switch. Explain where the definition of the
toString method that is being executed would be found.car and cdr, each capable of storing an integer.
Write a two-argument constructor for this class, and provide an accessor
and a mutator for each field.StringTokenizer, say -- belongs to?BufferedReader in = new BufferedReader(new InputStreamReader(System.in));Why is it advantageous to construct separate
InputStreamReader and
BufferedReader objects instead of simply using the read
method of System.in itself?System.out and System.err.main method receives two or more command-line
arguments?try-statement that catches an
unchecked exception?IOException? Which could throw a
NumberFormatException? How would you find out what exceptions, if
any, a particular method can throw?foo, one writes foo.length(). To compute the number
of elements in an array stored in the variable bar, one writes bar.length. Why are the parentheses required in the former case and
prohibited in the latter?vec and total are two local variables in a
method, declared thus:
int[] vec = new int[256]; int total;Suppose further that the statements immediately following these declarations assign values to all of the elements of
vec, perhaps by
filling them up with random numbers, as in Figure 2.4 on page 39 of our
textbook. Write further statements that would then compute the sum of the
elements of vec, storing that sum in total.for-loop, write a solution that does.doubles before you can do
arithmetic on them.)StringExperiments class."therein". (Hint: Use nested for-statements.)null reference to a variable
of some type that can hold objects, but it is not valid to apply the field
selection operator . to a null reference. Why?== operator appears between two variables of the same
non-primitive type, does it test whether the references stored in the
variables are identical or whether the objects referred to are equivalent?
What difference does it make?SwitchTester class that we developed today, how would
the output change if we added the statement vacuumCleaner = lamp; at
the beginning of the main method? Explain the differences.void in place of a return type) that do
not return values at all. Why would one ever define such a method? Of
what use could calling it possibly be, if the object to which it belongs
doesn't respond to the message?static mean when it modifies a
method declaration? What does it mean when it modifies a field
declaration?final mean when it modifies a field
declaration? What will happen if a program violates the restriction that
the final keyword tries to impose?while-loop "generally does something that can potentially alter the value
of expression [the entry test]; otherwise, the loop could be
infinite." What is an infinite loop? Give an example of a Java while-statement that would loop infinitely if executed. How would such a
loop manifest itself to the user of a program that included it?pow *= 2 is to replace the previous value of the variable pow
with its double. Using this knowledge, write a for-loop that would
print out the powers of 2 from 1 up to and including 1024.continue
statement, Weiss observes that his example
for (int i = 1; i <= 100; i++) {
if (i % 10 == 0)
continue;
System.out.println(i);
}
could be rewritten in other, equivalent ways. Suggest a way to get exactly
the same effect -- printing the positive integers up to 100, except those
that are multiples of 10 -- without using continue.break-statement in line 13?if-statement?if-statement that sets the int variable speed to the absolute value of the value of the int variable velocity.if-statement that prints out the string "large positive" if the current value of the double variable signand is greater than one billion, "large negative" if it is less
than minus one billion, and "small" otherwise.float and a
value of type double?++ is written in front of a variable,
what is its effect?& and && operators,
when their operands are Boolean expressions?
/* Summer: Computing the value of an arithmetic expression.
John David Stone
Department of Computer Science
Grinnell College
stone@cs.grinnell.edu
created January 21, 2008
last revised January 21, 2008
This program computes and prints out the value of an particular
arithmetic expression, appropriately labelled.
*/
public class Summer {
public static void main(String[] ignored) {
System.out.print("The sum of 5 and 7 is ");
System.out.print(5 + 7);
System.out.println(".");
}
}
int type and exact integers in Scheme?