Wednesday, November 25, 2015

Internal representation of Collections

Internal representation of  ArrayList

Internally an ArrayList uses an Object[].

As you add items to an ArrayList, the list checks to see if the backing array has room left. If there is room, the new item is just added at the next empty space. If there is not room, a new, larger, array is created, and the old array is copied into the new one.
Now, there is more room left, and the new element is added in the next empty space.

public static void main(String[] args) {
              ArrayList<String> list=new ArrayList<String>();
              }

Internal representation 

transient Object[] elementData;

public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};


Internal representation of  HashSet



Points to remember during HashSet


 If this set already contains the element, the call leaves the set
 Unchanged and returns false.

   HashSet doesn't provide any direct method for retrieving object e.g. get(Key key) from HashMap or get(int index) from List, only way to get object from HashSet is via Iterator. 

How Object is retrieved from HashSet

Now let's see the code for getting iterator for traversing over HashSet in Java. iterator() method from java.util.HashSet class returns iterator for backup Map returned by map.keySet().iterator() method.

       /**



     * Returns an iterator over the elements in this set.  The elements
     * are returned in no particular order.
     *
     * @return an Iterator over the elements in this set
     * @see ConcurrentModificationException
     */

    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }


No comments:

Post a Comment