Java Reference
In-Depth Information
// Get a synchronized view of the Set, s
Set ss = Collections.synchronizedSet(s);
// We need to iterate over elements of ss.
// Must get a lock on ss first (not on s)
synchronized(ss) {
Iterator iterator = ss.iterator();
// use iterator while holding the lock
while (iterator.hasNext()) {
Object obj = iterator.next();
// Do something with obj here
}
}
You need to follow the same logic while iterating over the key, value, or entry views of a synchronized Map . That
is, you must get a lock on the synchronized view of the Map while iterating over any of its views.
Checked Collections
Generics provide compile-time type-safety for collections. If a compiler determines that collections may have
elements violating its type declaration, it issues an unchecked compile-time warning. If you ignore the warning, your
code may bypass the generics rules at runtime. Let's consider the following snippet of code:
Set<String> s = new HashSet<>();
s.add("Hello");
a.add(new Integer(123)); // A compile-time error
You have declared the Set as a Set of String objects. You tried to add an Integer object to the Set . The compiler
made sure that you do not succeed in doing this.
Let's bypass the compiler check this time by using the following snippet of code:
Set<String> s = new HashSet< >();
s.add("Hello");
Set anythingGoesSet = s;
anythingGoesSet.add(new Integer(123)); // No runtime exception
This time, the compiler will issue an unchecked warning for the anythingGoesSet.add(new Integer(123))
statement because it has no way to know that you are adding an incorrect type of object to the Set . The result of the
above snippet of code is that you declared a Set of String objects and you were able to add an Integer object to it.
You will get a runtime exception when you try to read the Integer object as a String object, and it will be too late to
find out which line of code did it!
The Collections class helps you create a checked collection in which you will get a ClassCastException when
a piece of code attempts to add an element that violates the rule. This makes debugging the code easier. When you
create a checked collection, you mention the class type of the element it must hold. Adding any other type of element
will throw a ClassCastException . You can use the following static methods of the Collections class to get a checked
collection of a specific type:
<E> Collection<E> checkedCollection(Collection<E> c, Class<E> type)
<E> List<E> checkedList(List<E> list, Class<E> type)
 
Search WWH ::




Custom Search