Thursday, January 6, 2011

Making Collections read only

Making a Collection Read-Only

Making a collection read-only involves wrapping the collection in another object whose mutation methods all throw UnsupportedOperationException.

List stuff = Arrays.asList(new String[]{"m", "d"});

// Make a list read-only

List list = new ArrayList(stuff);

list = Collections.unmodifiableList(list);

try {

// Try modifying the list

list.set(0, "value");

} catch (UnsupportedOperationException e) {

// Can't modify

}

// Make a set read-only

Set set = new HashSet(stuff);

set = Collections.unmodifiableSet(set);

// Make a map read-only

Map map = new HashMap();

// Add key/value pairs ...

map = Collections.unmodifiableMap(map);

Shuffling the Elements of a List or Array

Shuffling the Elements of a List or Array

Use Collections.shuffle() to randomly reorder the elements in a list.

// Create a list

List list = new ArrayList();

// Add elements to list

// Shuffle the elements in the list

Collections.shuffle(list);

// Create an array

String[] array = new String[]{"M", "e", "g", "h", "a"};

// Shuffle the elements in the array

Collections.shuffle(Arrays.asList(array));

Comparing three implementations of List interface

Comparing three implementations of List interface 

Classes implementing List

Underlying data structure

Pros

Cons

ArrayList

array

1.        Faster to access by index

 

2.        Faster than Vector as methods are not synchronized

1.        Insertion or deletion in the middle is slower.

2.        Not thread –safe.

3.        Searching is sequential and hence not very efficient.

Vector

array

1.        Faster to access by index.

 

2.        Thread-safe access

1.        Insertion or deletion in the middle is slower.

2.        Slower than ArrayList as methods are synchronized.

3.        Searching is sequential and hence not very efficient.

LinkedList

doubly linked list

1.        Allows faster inserts/delete at any location*

2.        Faster than Vector as methods are not synchronized.

1.        Accessing element by index is slower.

2.        Searching is sequential and hence not very efficient.

Comparing three implementations of Set interface

Comparing three implementations of Set interface 

Classes implementing Set

Underlying data structure

Pros

Cons

HashSet

hash-table

1.        Useful when you want to impose only uniqueness among elements.

2.        Faster than other Set implementation as it does not need to maintain any order.

1.        Do not guarantee any order among elements.

2.        Not thread –safe.*

LinkedHashSet

hash-table

and

doubly linked list

1.        Maintains the insertion order.

1.        Slower than HashSet as it maintains the insertion order.

2.        Not thread –safe.*

TreeSet

tree

1.        Maintains the natural order among elements.

2.        You can impose different order by passing your own Comparator.

1.        Not thread –safe.*