Java Reference
In-Depth Information
sorted. Many common types (such as
String
and
Integer
) implement
Comparable
.
You can implement the
Comparable
interface in your
own classes by writing a method
compareTo
.
Self-Check Problems
Section 10.1:
ArrayList
s
1.
What is an
ArrayList
? In what cases should you use an
ArrayList
rather than an array?
2.
The next five questions refer to the following
String
elements:
["It", "was", "a", "stormy", "night"]
Write the code to declare an
ArrayList
containing these elements. What is the size of the list? What is its type?
3.
Write code to insert two additional elements,
"dark"
and
"and"
, at the proper places in the list to produce the
following
ArrayList
as the result:
["It", "was", "a", "dark", "and", "stormy", "night"]
4.
Write code to change the second element's value to
"IS"
, producing the following
ArrayList
as the result:
["It", "IS", "a", "dark", "and", "stormy", "night"]
5.
Write code to remove from the list any
String
s that contain the letter
"a"
. The following should be the list's
contents after your code has executed:
["It", "IS", "stormy", "night"]
6.
Write code to declare an
ArrayList
holding the first 10 multiples of 2: 0, 2, 4, . . . ,18. Use a loop to fill the list
with the proper elements.
7.
Write a method named
maxLength
that takes an
ArrayList
of
String
s as a parameter and that returns the length
of the longest
String
in the list. If your method is passed an empty
ArrayList
, it should return
0
.
8.
Write code to print out whether or not a list of
String
s contains the value
"IS"
. Do not use a loop.
9.
Given the
ArrayList
from problem 3, write code to print out the index at which your list contains the value
“stormy” and the index at which it contains “dark”. Do not use a loop.
10.
Given the
ArrayList
from problem 3, write a for-each loop that prints the uppercase version of each
String
in the
list on its own line.
11.
When the code that follows runs on an
ArrayList
of
String
s, it throws an exception. Why?
for (String s : words) {
System.out.println(s);
if (s.equals("hello")) {
words.add("goodbye");
}
}
12.
The code that follows does not compile. Why not? Explain how to fix it.
ArrayList<int> numbers = new ArrayList<int>();
numbers.add(7);
Search WWH ::
Custom Search