Do exercise 14.1 on pages 269-270.
Exercise 14.x1: Consider the following two nearly identical Java programs,
each of which uses an array of Integers, s
, as a stack,
with sp
serving the role of stack pointer. Each program
repeats 100 times the following two stages:
(1) push the Integers 0 up to 100000, (2) pop them all back off.
public class Bar { public static void main(String[] args){ Integer[] s = new Integer[100000]; int sp = 0; for(int i = 0; i < 100; i++){ for(int j = 0; j < 100000; j++){ s[sp++] = j; } while(sp > 0){ --sp; } } } }
public class Baz { public static void main(String[] args){ Integer[] s = new Integer[100000]; int sp = 0; for(int i = 0; i < 100; i++){ for(int j = 0; j < 100000; j++){ s[sp++] = j; } while(sp > 0){ s[--sp] = null; } } } }
Answer the following questions about these two programs:
Why might Bar be faster than Baz?
Why might Baz be faster than Bar?
By guessing which of these effects is larger, which of the two programs do you expect to be faster?
Which one actually is faster? How many times faster?
Exercise 15.x1: One can show the subtype relation on Java types by
drawing a diagram with arrows, where each arrow points from a subtype
to one of its supertypes. Arrows can be omitted that are implied by transitivity. As a simple example, if
the types under consideration are Integer
, Number
, and Object
,
one would draw an arrow pointing from Integer
to
Number
and a second arrow pointing from
Number
to Object
, but there would be no
need to show an arrow from Integer
directly to
Object
. Using this diagramming convention, show the
subtyping relation on List<?>
,
ArrayList<?>
,
List<Number>
, ArrayList<Number>
,
List<Integer>
, and ArrayList<Integer>
.