|
Spec-Zone .ru
спецификации, руководства, описания, API
|
List. Describe them, and note the limitations of each. Answer:
for statement:
List<Thing> list;
...
for (Thing thing : list) {
...
}
for statement together with an Iterator:
List<Thing> list;
...
for (Iterator<Thing> it = list.iterator(); it.hasNext(); ) {
Thing thing = it.next();
...
}
for statement together with an ListIterator:
List<Thing> list;
...
for (ListIterator<Thing> it = list.iterator(); it.hasNext(); ) {
Thing thing = it.next();
...
}
Set, List, Queue, and Map.
For each of the following four assignments, specify which of the four core
interfaces is best-suited, and explain how to use it to implement the assignment. List. Choose a random employee by picking a number between 0 and size()-1.Set. Collections that implement this interface don't allow the same element to be entered more than once.Map, where the keys are first names, and each value is a count of the number of employees with that first name.Queue. Invoke add() to add employees to the waiting list, and remove() to remove them.
import java.util.*;
public class SortMe {
public static void main(String args[]) {
SortedSet<StringBuffer> s = new TreeSet<StringBuffer>();
s.add(new StringBuffer("Red"));
s.add(new StringBuffer("White"));
s.add(new StringBuffer("Blue"));
System.out.println(s.first());
}
}
TreeSort elements must be instances of a class that implements
. StringBuffer does not.
import java.util.*;
public class Ran {
public static void main(String[] args) {
List<String> argList = Arrays.asList(args);
Collections.shuffle(argList);
for (String arg: argList) {
System.out.format("%s ", arg);
}
System.out.println();
}
}
List<String> and applies
String.trim to each element. To do this, you'll need to pick one of the three iteration idioms that you described in Question 1. Two of these will not give the result you want, so be sure to write a program that demonstrates that the method actually works! for statement does not allow you to modify the List. Using an Iterator allows you to delete elements, but not replace an existing element or add a new one. That leaves ListIterator:
import java.util.*;
public class ListTrim {
static void listTrim(List<String> strings) {
for (ListIterator<String> lit = strings.listIterator(); lit.hasNext(); ) {
lit.set(lit.next().trim());
}
}
public static void main(String[] args) {
List<String> l = Arrays.asList(" red ", " white ", " blue ");
listTrim(l);
for (String s : l) {
System.out.format("\"%s\"%n", s);
}
}
}