Java Reference
In-Depth Information
numbers.add(19);
System.out.println(numbers);
13. What is a wrapper class? Describe the difference between an int and an Integer .
Section 10.2:The Comparable Interface
14. Describe how to arrange an ArrayList into sorted order. What must be true about the type of elements in the list in
order to sort it?
15. What is a natural ordering? How do you define a natural ordering for a class you've written?
16. Consider the following variable declarations:
Integer n1 = 15;
Integer n2 = 7;
Integer n3 = 15;
String s1 = "computer";
String s2 = "soda";
String s3 = "pencil";
Indicate whether the result of each of the following comparisons is positive, negative, or 0 :
a. n1.compareTo(n2)
b. n3.compareTo(n1)
c. n2.compareTo(n1)
d. s1.compareTo(s2)
e. s3.compareTo(s1)
f. s2.compareTo(s2)
17. Use the compareTo method to write code that reads two names from the console and prints the one that comes first
in alphabetical order. For example, the program's output might look like the following:
Type a name: Tyler Durden
Type a name: Marla Singer
Marla Singer goes before Tyler Durden
18. Write code to read a line of input from the user and print the words of that line in sorted order, without removing
duplicates. For example, the program output might look like the following:
Type a message to sort: to be or not to be that is the question
Your message sorted: be be is not or question that the to to
Exercises
1. Write a method called averageVowels that takes an ArrayList of String s as a parameter and returns the average
number of vowel characters (a, e, i, o, u) in all String s in the list. If your method is passed an empty ArrayList ,it
should return 0.0 .
2. Write a method called swapPairs that switches the order of values in an ArrayList of String s in a pairwise
fashion. Your method should switch the order of the first two values, then switch the order of the next two, then the
next two, and so on. If the number of values in the list is odd, the method should not move the final element. For
example, if the list initially stores (“to”, “be”, “or”, “not”, “to”, “be”, “hamlet”), your method should change the
list's contents to (“be”, “to”, “not”, “or”, “be”, “to”, “hamlet”).
Search WWH ::




Custom Search