Java Collections Cheat Sheet

Java Collections Framework



Collections are most widely concept in java. Most of the time I get confused, when to use, what type of collections. If its the same with you, this post would make an  attempt to clear that confusion, I tried to list the parameters that can be used to make decision.

Topics:
Collections
Collections Interfaces
Collections Cheat Sheet
Collections Examples

Collection Framework:
Java Collection framework provides mechanism to store, retrieve and manipulate objects.
All collection interfaces and classes are present in java.util package.


Core Interfaces for Collections
Collection  is the root of the collection hierarchy

Sorted Set: A Set that maintain elements in sorted ascending order.
Sorted Map: A Map that maintains keys in sorted ascending order.

Decision to use which collection class depends on following factors:
  • Ordered
  • Duplicates
  • Synchronized
  • Not Ordered

Collection Interfaces:

Interfaces Definition has Duplicates
List It’s a data structure where stored objects can be accesible using index. Yes.
Map Data structure allows key value pair storage. No duplicate keys are allowed.Values can be duplicate.
Set it’s a data structure  that doesnot allow duplicate storage of elements . Elements cannot be accessed using index. No. Set doesnot allow duplicate elements
Queue ordered in on a FIFO Yes.
Deque ordered elements in either  LIFO and FIFO. Its a double-ended-queue is a linear collection of elements that supports the insertion and removal of elements at both end points Yes.


Collection Cheat Sheet:

Ordered : Elements are stored in a order and when iterator is used over this elements, user knows in what order elements can be retrieved.
Sorted : elements are stored in sorted order.This sorting order depends on natural ordering, or by a Comparator.
Thread safe:  Methods are implemented using synchronized. this can be used in a multi threaded environment. 

classes with collections. Maps doesn't implement interface Collection



Below parameters can be used to make choice of what data structures can be used.


Collection Name Implements Interface Ordered Sorted synchronized
(Thread safe)
 When to use it
Array List List  Yes No No 1. when retrieval/accessing elements  is primary aim
2. Random access to elements using their index
Vector List  Yes No Yes when elements  thread safety is more important with retrieval of elements
Linked List List, Deque  Yes No No  When insertion and deletion is primary task, not accessing the elements.
HashSet Set  No No No If the requirement is only to have elements unique.
LinkedHashSet Set Yes No No If the requirement is to returns elements in the same order of insertion
TreeSet Set Yes Yes No Elements needs to be stored in sorted order. Default is ascending order
HashMap Map No No No If the requirement is faster access. No synchronization needed
HashTable Map No No Yes Used for faster access. No null keys are allowed
LinkedHashMap Map Yes No No If user wants  retrieve keys is the insertion order. Predictable iteration order is the requirement
TreeMap Map Yes Yes No If the requirement is sorted Map, with key value pair storage
ArrayDeque Deque Yes No No No Null values.  Cannot access elements using index. Can be used which allows efficient insertion and deletion at both ends. 
PriorityQueue Queue Yes No No No Null values.  Item that is removed from the queue is not necessarily the first one that was added. Rather, it is whatever item in the queue has the highest priority. 

Collection Examples:
 All the examples are compiled on java 1.7 update 21



ArrayList Example:

Standard Arrays are fixed cannot  grow and shrink in size .  ArrayList solves this problem. ArrayList can dynamically increase or decrease in size. It has a  initial size, When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk. It can be asssed with indexes.

import java.util.ArrayList;
public class ArrayListExample {
    public static void main(String[] args) {
       
        ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
        arrayList.add(45);
        arrayList.add(48);
        arrayList.add(4);
        // retrieve an element using index
        System.out.println( " Accessing using index " + arrayList.get(2) );
        arrayList.remove(1);
        // let us print all the elements
        System.out.println( " print ArrayList elements " + arrayList) ;

    }

}


HashSet Example:
import java.util.HashSet;

public class HashSetExample {

    public static void main(String[] args) {

        HashSet<Integer> hashset = new HashSet<Integer>();
      
        //returns true if the element is inserted
        if ( hashset.add(34) )
            System.out.println(" Element is inserted");
        else
            System.out.println("Element Cannot be inserted, duplicate");
  
        if ( hashset.add(34) )
            System.out.println(" Element is inserted");
        else
            System.out.println("Element Cannot be inserted, duplicate");
      
      
      
  
    }

}




 TreeMap Example:

   import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.TreeMap;
   
    public class TreeMapExample {
        public static void main(String[] args) {
            TreeMap<String,Integer> treemap = new TreeMap<String,Integer>();
            treemap.put("first", 1);
            treemap.put("second", 2);
            treemap.put("three", 3);
            treemap.put("four", 4);
           
           
            System.out.println(treemap);
            Set<Entry<String, Integer>> entrySet = treemap.entrySet();
            Iterator<Entry<String, Integer>> iterator = entrySet.iterator();
           
            while(iterator.hasNext())
            {
                Map.Entry me = (Map.Entry)iterator.next();
                System.out.println(me.getKey());
               
            }
        }
   
    }






Good to know facts:
=======================================================
1. When to use
Hash Map :Inserting , deletion are required.
Tree Map: To traverse already sorted list

=======================================================
List of thread safe classes in collection

Vector, Hash table,  Stack are synchronized classes can be termed as thread-safe..

=======================================================
What is difference between HashMap vs  Hashtable
------------------------------------------------------------------------------------
HashMap                                                  |         HashTable
------------------------------------------------------------------------------------
Allows null keys and null values                |       Doesn't allow null values
Non Synchronized(not thread safe)            |      Synchronized (thread safe)

===================================================

Sets doesn't allow duplicates.

===================================================

Maps duplicate keys are not allowed.

=================================================


HTTP Cookies

HTTP Cookies


HTTP is a stateless protocol. Whenever a user makes a request to the server, the server opens a connection, downloads the page accessed and closes the connection. If the same user comes for the second time, the browser won't be having any idea whether the request came from same user or a different user.

 Now how does it matter to a  novice user.



Imagine accessing any social networking site and every page navigating like a profile visit you do, requiring user name/password like an ATM transaction in India. This would mean a nightmare for the user and head ache for the social networking site in handling repeating logins.


From a technical perspective, this would mean every page navigated by user is a new transaction, (without any cookies concept), for every request the social network site server would say, and who are you? Prove your identity.




Cookies solves this problem by storing a plain text data in a user agent (we call it a browser). Post sign-in, on every page accessed by the user, browser returns this text data (Cookie) to the server hosting the social networking site. The server would have a mechanism to decrypt text data, and validate the user. This ensures that the user doesn't have to log-in every time for every page access and on the flip side, the server got a mechanism to valid their users for every page access, without passing username and password for every transaction.

Contents:
  1. Name Cookies
  2. About Cookies
  3. Cookies Storage
  4. Cookies Content
  5. Types of Cookies
  6. Advantages for Cookies
  7. Attacks using Cookies
  8. Cookie Guidelines- Laws for Cookies

Name Cookies:


No one has exact information about this. so do I :)   
The name Cookies comes from the word 'Magic cookie' and term came from Netscape Corporation.


About Cookies:


A Cookie is a small text data which is created and stored in the user’s browser by the web application. This information is passed on to the web server by the browser on subsequent request, facilitating session management, personalization.

Cookies Content



Name: Each cookie will have a Name. This name would enable each cookie to be identified uniquely.
Name is mandatory for any cookie.
Content: This is the actual text that stores the information. The web application would retrieve this value to make a decision. Cookie content is mandatory for cookie.
Domain of a cookie: Each cookie has a domain which is related to the domain of the web application that has created it. It helps in determining the scope of a cookie.
This domain helps in serving the privacy policy, where the guidelines say that a browser has to send cookies specific to that particular domain only which means that though a browser has cookies related to both facebook and gmail stored in it. It cannot send the facebook cookies to the gmail server.
             Each domain can have a maximum of 20 cookies.

Path: This value along with the Domain name helps in determining the scope of a cookie.  Its a  URI.
Expires: This indicates the expiration time or maximum age for a cookie.
 If time is specified, it must be a GMT time, with
the date specified in the form of “Wdy, DD Mon YYYY HH:MM:SS GMT” indicating the exact date/time the cookie will expire.
Secure: HttpOnly attribute determines that cookie is meant to be used in secure connection only .i.e SSL.


Cookies Storage 
     
       Cookies are stored in the client machine. It can either be the browser(chrome, firefox) or client hard disk.
Server doesn't have to maintain these cookies.


Types of Cookies

 Cookies are classified into two types based on their storage.
  1. Session cookies 
  2. Persistent Cookies
Session cookies are specific to a browser session. These are stored in the memory of a browser. If a user closes the browser, these cookies would be deleted.

Example would be User ID of a particular user login to a site 

Persistent cookies: These cookies are stored on user’s hard disk in a file. Even if browsers are closed and opened, these cookies will not be deleted.

Example would be any site with a different language offering would love to show the site in your preferred language on your second visit without you having to set the language preference every time.

Advantages for Cookies 

  1. Ability to personalize information: It provides a mechanism for the server to show information more relevant to a user. Example: when a user types language, the search engine would return different results for a different user.  A Software professional might get list of programming languages and a general user gets list of regional languages in that specific area.
  2. Single Sign on for all web applications like Facebook, gmail, any banking site. We call it session management.
  3. Storing demographic information like country, language, preferences etc.
    Attacks using Cookies and disadvantages.

    1. Cookies can easily be stolen using cross site scripting, this would allow replay attacks. If the server, doesn't have a mechanism to prevent replay attacks, security of the sites is compromised.
    2. A web server doesn't have a mechanism to prevent user from deleting or tampering cookies. Deleting cookies, results in failure of task of personalization.
     3. No Central storage for cookies, each browser stores cookies in its own location. With multiple browsers installed on a single machine, a preference set on one browser is not known to the other browser.

    Cookie Guidelines- Laws for Cookies

     People call it Cookie law:
    1. Websites to obtain consent from visitors to store or retrieve any information on a computer
    2. To protect online privacy by making consumers aware of how information about them is collected by websites, and enabling them to choose whether or
    Facebook privacy for cookies can
    be found at highlighted region

    not they want it to happen.


    Example:

    yahoo privacy policy
    http://info.yahoo.com/privacy/us/yahoo/cookies/
    Facebook privacy policy can be found here:
    https://www.facebook.com/help/cookies



    Thanks to my friends in supporting me. I wish, i could name them here, only if the world was not so bad.