1)
Look up the Random
class at http://java.sun.com/j2se/1.4.2/docs/api/index.html.
a.
How many methods are
used? 10
b.
What is the difference
between nextInt(int ) and nextInt()?
nextInt(int) allows you to set the maximum random value to be returned.
2)
Using the Random class,
what would be the maximum and minimum values of:
a.
nextInt(6) + 5; 5 to 10
b.
nextInt (1) + 1; 1 //kind of silly, huh?
c.
nextInt (11) + 20; 20 to 30
d.
nextInt (21) – 10;
3)
How would you write the
code to produce a random number between -5 and 5?
import java.util.Random;
public void getRandom(){
Random i = new Random();
i.nextInt(11) – 5;
}
4)
Describe how a hash map
works.
A hash map consists of a key and a value. The key is used to reference
the value. This would be useful, for instance, if you must track students by
their ID number. You could construct a hash map consisting of the student’s
name as the key, and the ID number as the value. This way you could refer to the
student by name rather than ID number.
5)
What is information
hiding and why is it useful?
Information hiding is code written so that it is not necessary to
actually view the code to use it. This is useful because it makes it
unnecessary to re-write code to perform common tasks. For example, ArrayList is
a class. We do not need to know how the add() method in ArrayList works to use
it. We only need to know the name of the method and the parameters it takes.
With information hiding, we can write many programs that incorporate an
ArrayList without writing (or even seeing) the code for it.
6)
How do you initialize an ArrayList? A
fixed-size array?
a.
ArrayList A = new
ArrayList();
b.
private int[] a = new int[10];
7)
What is the difference
between ArrayList and a fixed-size Array?
ArrayList is dynamic (changes in size) and can only hold objects. ArrayList is a class and has methods
associated with it that we call to perform actions on the data in the list.
A fixed- size array is restricted as to the number of values it can hold
and can only hold one data type.
8)
Give an example in
which it would be better to use ArrayList.
Answers will vary.
When you need to create a collection of objects.
9) Give an example in which it would be better to use a fixed-size array.
Answers will vary.
When the size of the array and the data type are known.
10)
Draw a graphical
depiction of the following:
a. ArrayList myArray = new ArrayList();
myArray.add(“C201”);
0 1
myArray.add(“C202”);
![]()
![]()
String “C201” String “C202”
b.
int [] myArray2 = { 21, 34, 79, 292 }
0 1
2 3
292 79 34 21
c.
String[] myArray3 = new String[5];
0 1 2 3 4
String <null> String <null> String <null> String <null> String <null>
11)
Write the code to call
an external method with the signature ‘public void giveName(String
name)’ from a class called Pet. (You have been provided the first line of code)
Pet dog = new Pet ();
dog.giveName(“Cliff”);