Java Collection

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Hashmap-- how to minimize collision

- keep the number of buckets to a prime number - improve the quality of our hashing function, by multiplying character codes by a small constant - create a resizing function to address collision as it occurs

ArrayList v LinkedList v Vector

- ArrayList is implemented as a resizable array. As more elements are added to ArrayList, its size is increased dynamically. It's elements can be accessed directly by using the get and set methods, since ArrayList is essentially an array. - LinkedList is implemented as a double linked list. Its performance on add and remove is better than Arraylist (no shifting), but worse on get and set methods. - Vector is similar with ArrayList, but it is synchronized (if one thread is working on vector, no other thread can get a hold of it). ArrayList is a better choice if your program is thread-safe. Vector and ArrayList require space as more elements are added. Vector each time doubles its array size, while ArrayList grow 50% of its size each time. - LinkedList implements Queue interface which adds more methods than ArrayList and Vector, such as offer(), peek(), poll(), etc.

Hashmap - what put( ) method does

- First of all, the key object is checked for null. If the key is null, the value is stored in table[0] position. Because hashcode for null is always 0. - Then on next step, a hash value is calculated using the key's hash code by calling its hashCode() method. This hash value is used to calculate the index in the array for storing Entry object. JDK designers well assumed that there might be some poorly written hashCode() functions that can return very high or low hash code value. To solve this issue, they introduced another hash() function and passed the object's hash code to this hash() function to bring hash value in the range of array index size. - Now indexFor(hash, table.length) function is called to calculate exact index position for storing the Entry object.

HashMap vs ArrayList

- different interfaces - maintenance of insertion order - memory consumption (ArrayList stores the elements only as value and maintain internally the indexing for every element. While HashMap stores elements with key and value pair, i.e. two objects. So HashMap takes more memory comparatively.) - duplicates - fetching an element - storing nulls (In ArrayList, any number of null elements can be stored. While in HashMap, only one null key is allowed, but the values can be of any number.)

How to convert an array of String to arraylist?

//String array String[] words = {"ace", "boom", "crew", "dog", "eon"}; //Use Arrays utility class List wordList = Arrays.asList(words); //Now you can iterate over the list

Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is Hashing

A way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties

Array v ArrayList

Array: Simple fixed sized arrays that we create in Java ArrayList : Dynamic sized arrays in Java that implement List interface. An array is basic functionality provided by Java. ArrayList is part of collection framework in Java. Therefore array members are accessed using [], while ArrayList has a set of methods to access elements and modify them. Array can contain both primitive data types as well as objects of a class depending on the definition of the array. However, ArrayList only supports object entries, not the primitive data types.

ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add or delete the elements from both the ends. ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Reverse the list

Collections.reverse(list);

Deque Interface

Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both the side. Deque stands for a double-ended queue which enables us to perform the operations at both the ends.

Hashmap - Entry Class

HashMap has an nested static class Entry <K, V>

HashSet, LinkedHashSet, TreeSet

HashMap offers O( 1) lookup and insertion. If you iterate through the keys, though, the ordering of the keys is essentially arbitrary. It is implemented by an array of linked lists. TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through the keys in sorted order, you can.This means that keys must implement the Comparable interface. TreeMap is implemented by a Red-BlackTree. LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by their insertion order. It is implemented by doubly-linked buckets. Generally, unless there is a reason not to, you would use HashMap.That is, if you need to get the keys back in insertion order, then use LinkedHashMap. lf you need to get the keys back in their true/natural order, then use TreeMap, Otherwise, HashMap is probably best It is typically faster and requires less overhead.

HashSet

HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to store the elements in the HashSet. It contains unique items.

Set Interface

It extends the Collection interface. It represents the unordered set of elements which doesn't allow us to store the duplicate items. We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.

LinkedHashSet

It extends the HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits null elements. O(1) lookup and insertion. Keys are ordered by their insertion order. It is implemented by doubly-linked buckets.

Why do we use Set interface?

It models the mathematical set in set theory. Set interface is like List interface but with some differences. First, it is not ordered collection. So no ordering is preserved while adding or removing elements. The main feature it does provide is "uniqueness of elements". It does not support duplicate elements. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements. Based on above reasons, it does not have operations based on indexes of elements like List. It only has methods which are inherited by Collection interface.

Iterator interface

Iterator interface provides the facility of iterating the elements in a forward direction only. The Iterable interface is the root interface for all the collection classes. The Collection interface extends the Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable interface. hasNext( ) next( ) remove( ) Iterator<T> iterator()

LinkedList

LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can store the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the manipulation is fast because no shifting is required.

ArrayList v LinkedList performance

LinkedList should be preferred if: 1) there are no large number of random access of element 2) there are a large number of add/remove operations

List Interface

List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can store the ordered collection of objects. It can have duplicate values. List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack. List <data-type> list1= new ArrayList(); List <data-type> list2 = new LinkedList(); List <data-type> list3 = new Vector(); List <data-type> list4 = new Stack();

Queue Interface

Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold the elements which are about to be processed. There are various classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.

SortedSet Interface

SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet provides the additional methods that inhibit the natural ordering of the elements.

ArrayList Class

The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of different data types. The ArrayList class maintains the insertion order and is non-synchronized. The elements stored in the ArrayList class can be randomly accessed. Note: The default initial capacity of an ArrayList is pretty small. It is a good habit to construct the ArrayList with a higher initial capacity. This can avoid the resizing cost.

What is the Java Collection Framework?

The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has: Interfaces and its implementations, i.e., classes; Algorithm

Collection interface

The Collection interface is the interface which is implemented by all the classes in the collection framework. It declares the methods that every collection will have. In other words, we can say that the Collection interface builds the foundation on which the collection framework depends. Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection c), void clear( ), etc. which are implemented by all the subclasses of Collection interface.

PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.

Hierarchy of Collection Framework

The java.util package contains all the classes and interfaces for the Collection framework.

Stack

The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.

Vector

Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized and contains many methods that are not the part of Collection framework.

Hashset-- keys requirements

a good key object must provide same hashCode() again and again, no matter how many times it is fetched. Similarly, same keys must return true when compare with equals() method and different keys must return false.

implements vs extends

extends is for extending a class. - A class can extend a superclass - An interface can extend another interface implements is for implementing an interface - A class can implement an interface - An interface never implements

ArrayList example

import java.util.*; class TestJavaCollection1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Ravi");//Adding object in arraylist list.add("Vijay"); list.add("Ravi"); list.add("Ajay"); //Traversing list through Iterator Iterator itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }

A hash function

return the same hash code each and every time when the function is applied on same or equal objects. In other words, two equal objects must produce the same hash code consistently.

TreeSet

the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order. O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through the keys in sorted order, you can.This means that keys must implement the Comparable interface. TreeMap is implemented by a Red-BlackTree.

Why do we use List interface?

to manipulate the collection based on index location of element. These methods can be grouped as search, get, iteration and range view. All above operations support index locations.

Hashmap- How collisions are resolved

two unequal objects can have the same hash code value, how two different objects will be stored in same array location called bucket. Entry objects are stored in linked list form. When an Entry object needs to be stored in particular index, HashMap checks whether there is already an Entry. If there is no entry already present, the entry object is stored in this location. If there is already an object sitting on calculated index, its next attribute is checked. If it is null, and current entry object becomes next node in linkedlist. If next variable is not null, procedure is followed until next is evaluated as null. Add the another value object with same key as entered before: after determining the index position of Entry object, while iterating over linkedlist on calculated index, HashMap calls equals method on key object for each entry object. All these entry objects in linkedlist will have similar hashcode but equals() method will test for true equality. If key.equals(k) will be true then both keys are treated as same key object. This will cause the replacing of value object inside entry object only.


Set pelajaran terkait

Exam 1 Business Research Methods

View Set

That's Pretty Clever! Characters in The Number Devil

View Set