Java Reference
In-Depth Information
18. Scanner console = new Scanner(System.in);
System.out.print("Type a message to sort: ");
String message = console.nextLine();
ArrayList<String> words = new ArrayList<String>();
Scanner lineScan = new Scanner(message);
while (lineScan.hasNext()) {
words.add(lineScan.next());
}
System.out.print("Your message sorted: ");
Collections.sort(words);
for (String word : words) {
System.out.print(word + " ");
}
System.out.println(); // to end the line of output
Chapter 11
1. You should use a LinkedList when you plan to add or remove many values to or
from the front or back of the list, or when you plan to make many filtering passes
over the list during which you remove certain elements.
2. The code shown would perform better with an ArrayList , because it calls the get
method many times using indexes in the middle of the list. This is a slow operation
for a LinkedList .
3. An iterator is an object that represents a position within a list and enables you to
view or make changes to the elements at that position. Iterators are often used with
linked lists because they retain the position in the list, so you don't have to call
expensive list methods like get , add , or remove many times.
4. public static int countDuplicates(LinkedList<Integer> list) {
int count = 0;
Iterator<Integer> i = list.iterator();
int prev = i.next();
while (i.hasNext()) {
int next = i.next();
if (prev == next) {
count++;
 
Search WWH ::




Custom Search