1Java for SE
2Java for SE
List
If your data is linear or having multiple copies of same data
or containing null data, this is the better data structure for the
scenario.
There are two basic implementations based on the way you
need to access the data..
•ArrayList.
‒Array based implementation, good for Random data access.
•LinkList.
‒Doubly link list based implementation, good for sequential data
access.
3Java for SE
Let's compare.
Since, Linked based implementation has to keep track on neighbors, it
consume more memory than an Array.
4Java for SE
Operation ArrayList LinkedList
Insert O(n) O(1)
Delete O(n) O(1)
Search O(1) O(n)
Common to both
•They both maintain the elements insertion order.
•Both these classes are non-synchronized.
‒Use, Collections.synchronizedList method for explicitly thread
safe.
•These classes are fail-fast.
‒if list is structurally modified at any time after the iterator is
created unless using, iterator's own remove method, this will throw
ConcurrentModificationException
5Java for SE
6Java for SE
Set
If your data do not contains duplicates use a set.
Commonly used implementations.
•HashSet.
‒Hash Table based implementation but there is no grantee on the
order.
•LinkedHashSet.
‒Hash Table and link list based implementation which is having
insertion order.
Performance of both above will be determine by the load factor
7Java for SE
Points to remember on Set.
•Doesn’t maintain any order, the elements would be returned in
any random order.
•No duplicates.
•Allows a null value ( only one )
•These classes are fail-fast.
•Not thread safe
8Java for SE
How ?
9Java for SE
10Java for SE
Map
Use MAP implementation if your data can be model as a Key
Value pair.
Some notable implementations
•HashMap.
•WeakHashMap
You can use an object as Key for the map but using null value
as key is not permitted.
11Java for SE
Map
Use MAP implementation if your data can be model as a Key
Value pair.
Some notable implementations
•HashMap.
•WeakHashMap
You can use an object as Key for the map but using null value
as key is not permitted.
12Java for SE
Map Performance
Searching an entry from a Map should take consistent
amount of time.It does not matter you have 10000 record or 1
record in the map. We call it O(1) performance.
But this depends on a factor called a load factor.
Load Factor = available data size / total capacity.
It's being proven that, O(1) only be achievable if the load
factor is near to 0.75
13Java for SE
Map Performance
What will happen if you instantiate a Map as follow.
Map<String,String> users = new HashMap<>();
Other Constructors
HashMap()
HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
HashMap(Map<? extends K,? extends V> m)
14Java for SE
Tree Map & TreeSet
By default, hash map or weak hashmap or HashSet do not
offer natural ordering. That means, it does not grantee the
insert order. But in some cases we might need a map
implementation where it all ways orders itself based on the
given ordering.
And it ensure, O(log(n)) performance for all the operations.
15Java for SE
Before pick a collection.
•Predict the amount of data
.
•What is my most common operation ( insert , delete , search )
•What is my data.
‒Do I have unique date or not.
‒Do I have null values.
•Do I expect an ordering ?
16Java for SE
Collection Framework
Collection
Map Sett
17Java for SE
List
Collections.
Collections is a utility class which provide plenty of useful
methods. Collection class provide few immutable , singleton
objects to safeguards us from returning null values.
Option 1 :
public static final List EMPTY_LIST
Option 2:
List<String> s = Collections.emptyList();
We can use both options instead of returning a null, but use
Option 2 since Option 1 does not provide the type safety.
18Java for SE
Collections.
Some other useful methods in collections.
By default, most of the collection are not thread safe, but with the
help of Collections we can make them safe.
List list = Collections.synchronizedList(new ArrayList());
Collections.replaceAll
Collections.sort
Collections.reverse
19Java for SE
Collections .
For most of the collections or collection operations such as
searching, sorting, removing it requires objects which are
inherited from Comparable interface.
Ex .
•Calling Collections.sort and Collections.binarySearch
.
•Calling Arrays.sort and Arrays.binarySearch
•Using objects as keys in a TreeMap
•Using objects as elements in a TreeSet
20Java for SE
Diamond Operator
Old approach:
Map<String,MyClass> classes = new HashMap<String,MyClass>();
New approach:
Map<String,MyClass> classes = new HashMap<>();
21Java for SE
Avoid return null values.
What is the issue here ?
List<Course> retreiveCourses(List<Course> courses){
List<Course> courses= null;
// Invoke db but it returns null
return courses;
}
● Caller has to be careful since method may return null values
instead of a List.This will introduce more checks in callers
side.
● Returning a Null from a method is an anti pattern.
22Java for SE
Questions
23

Java - Collections

  • 1.
  • 2.
  • 3.
    List If your datais linear or having multiple copies of same data or containing null data, this is the better data structure for the scenario. There are two basic implementations based on the way you need to access the data.. •ArrayList. ‒Array based implementation, good for Random data access. •LinkList. ‒Doubly link list based implementation, good for sequential data access. 3Java for SE
  • 4.
    Let's compare. Since, Linkedbased implementation has to keep track on neighbors, it consume more memory than an Array. 4Java for SE Operation ArrayList LinkedList Insert O(n) O(1) Delete O(n) O(1) Search O(1) O(n)
  • 5.
    Common to both •Theyboth maintain the elements insertion order. •Both these classes are non-synchronized. ‒Use, Collections.synchronizedList method for explicitly thread safe. •These classes are fail-fast. ‒if list is structurally modified at any time after the iterator is created unless using, iterator's own remove method, this will throw ConcurrentModificationException 5Java for SE
  • 6.
  • 7.
    Set If your datado not contains duplicates use a set. Commonly used implementations. •HashSet. ‒Hash Table based implementation but there is no grantee on the order. •LinkedHashSet. ‒Hash Table and link list based implementation which is having insertion order. Performance of both above will be determine by the load factor 7Java for SE
  • 8.
    Points to rememberon Set. •Doesn’t maintain any order, the elements would be returned in any random order. •No duplicates. •Allows a null value ( only one ) •These classes are fail-fast. •Not thread safe 8Java for SE
  • 9.
  • 10.
  • 11.
    Map Use MAP implementationif your data can be model as a Key Value pair. Some notable implementations •HashMap. •WeakHashMap You can use an object as Key for the map but using null value as key is not permitted. 11Java for SE
  • 12.
    Map Use MAP implementationif your data can be model as a Key Value pair. Some notable implementations •HashMap. •WeakHashMap You can use an object as Key for the map but using null value as key is not permitted. 12Java for SE
  • 13.
    Map Performance Searching anentry from a Map should take consistent amount of time.It does not matter you have 10000 record or 1 record in the map. We call it O(1) performance. But this depends on a factor called a load factor. Load Factor = available data size / total capacity. It's being proven that, O(1) only be achievable if the load factor is near to 0.75 13Java for SE
  • 14.
    Map Performance What willhappen if you instantiate a Map as follow. Map<String,String> users = new HashMap<>(); Other Constructors HashMap() HashMap(int initialCapacity) HashMap(int initialCapacity, float loadFactor) HashMap(Map<? extends K,? extends V> m) 14Java for SE
  • 15.
    Tree Map &TreeSet By default, hash map or weak hashmap or HashSet do not offer natural ordering. That means, it does not grantee the insert order. But in some cases we might need a map implementation where it all ways orders itself based on the given ordering. And it ensure, O(log(n)) performance for all the operations. 15Java for SE
  • 16.
    Before pick acollection. •Predict the amount of data . •What is my most common operation ( insert , delete , search ) •What is my data. ‒Do I have unique date or not. ‒Do I have null values. •Do I expect an ordering ? 16Java for SE
  • 17.
  • 18.
    Collections. Collections is autility class which provide plenty of useful methods. Collection class provide few immutable , singleton objects to safeguards us from returning null values. Option 1 : public static final List EMPTY_LIST Option 2: List<String> s = Collections.emptyList(); We can use both options instead of returning a null, but use Option 2 since Option 1 does not provide the type safety. 18Java for SE
  • 19.
    Collections. Some other usefulmethods in collections. By default, most of the collection are not thread safe, but with the help of Collections we can make them safe. List list = Collections.synchronizedList(new ArrayList()); Collections.replaceAll Collections.sort Collections.reverse 19Java for SE
  • 20.
    Collections . For mostof the collections or collection operations such as searching, sorting, removing it requires objects which are inherited from Comparable interface. Ex . •Calling Collections.sort and Collections.binarySearch . •Calling Arrays.sort and Arrays.binarySearch •Using objects as keys in a TreeMap •Using objects as elements in a TreeSet 20Java for SE
  • 21.
    Diamond Operator Old approach: Map<String,MyClass>classes = new HashMap<String,MyClass>(); New approach: Map<String,MyClass> classes = new HashMap<>(); 21Java for SE
  • 22.
    Avoid return nullvalues. What is the issue here ? List<Course> retreiveCourses(List<Course> courses){ List<Course> courses= null; // Invoke db but it returns null return courses; } ● Caller has to be careful since method may return null values instead of a List.This will introduce more checks in callers side. ● Returning a Null from a method is an anti pattern. 22Java for SE
  • 23.

Editor's Notes

  • #12 WeakHashMap key will be automatically removed by the GC if ref is no longer exist
  • #13 WeakHashMap key will be automatically removed by the GC if ref is no longer exist
  • #14 WeakHashMap key will be automatically removed by the GC if ref is no longer exist or
  • #15 Default will be .75 with 16 size
  • #16 WeakHashMap key will be automatically removed by the GC if ref is no longer exist
  • #17 There are empty collections for set , map , list If field being used, compiler will throw a warning Try out other methods, ex, sorted set
  • #19 Navigate through api documentation
  • #20 Sync methods for list, set map Check out all other methods
  • #21 Sync methods for list, set map Check out all other methods
  • #22 Sync methods for list, set map Check out all other methods
  • #24 &amp;lt;number&amp;gt;