Java Reference
In-Depth Information
// Reverse the list
Collections.reverse(list);
System.out.println("After Reversing: " + list);
// Swap elements at indexes 1 and 3
Collections.swap(list, 1, 3);
System.out.println("After Swapping (1 and 3): " + list);
// Rotate elements by 2
Collections.rotate(list, 2);
System.out.println("After Rotating by 2: " + list);
List: [John, Richard, Donna, Ken]
After Shuffling: [Ken, Donna, Richard, John]
After Reversing: [John, Richard, Donna, Ken]
After Swapping (1 and 3): [John, Ken, Donna, Richard]
After Rotating by 2: [Donna, Richard, John, Ken]
Creating Different Views of a Collection
You can get a
LIFO Queue
view of a
Deque
using the
asLifoQueue()
static method of the
Collections
class:
•
<T> Queue<T> asLifoQueue(Deque<T> deque)
Some
Map
implementations have corresponding
Set
implementations too. For example, for
HashMap
, you have a
HashSet
; for
TreeMap
, you have a
TreeSet
. If you want to use a
Map's
implementation as a
Set
implementation, you
can use the
newSetFromMap()
static method of the
Collections
class:
<E> Set<E> newSetFromMap(Map<E, Boolean> map)
Note that the idea is to use the implementation of the
Map
as a
Set
, not to share elements between a
Map
and a
Set
. This is the reason that the
Map
must be empty when you use it in this method and you are not supposed to use
the
Map
directly at all. There is a
WeakHashMap
implementation class for the
Map
. However, there is no corresponding
WeakHashSet
implementation class for the
Set
. Here is how you can get a weak hash set implementation:
•
Map map = new WeakHashMap(); // Do not populate and use the map
Set wSet = Collections.newSetFromMap(map); // You can use wSet
Use the weak hash set
wSet
as a
Set
and it acts as the
WeakHashMap
implementation. Since you are not
supposed to use the
Map
object, it is better to use the following statement to create the set using the
WeakHashMap
implementation class:
// Do not keep the reference of the Map
Set wSet = Collections.newSetFromMap(new WeakHashMap());
When the JVM needs memory, the garbage collector can remove elements from
wSet
as it does from any
WeakHashMap
. By using one line of code, you get a
Set
that has features of a
WeakHashMap
.