Showing posts with label Collection. Show all posts
Showing posts with label Collection. Show all posts

Sunday, 8 May 2016

How to evaluate a postfix expression ?


Postfix notation represents a algebraic expression.
These are evaluated faster than infix notation, as ( ) are not required.

Algorithm - using Stack

  • For each element in postfix string
    • if element is an operand
      • push element into Stack => Operand
    • else  // Operator
      • Pop from Stack => Operand 1
      • Pop from Stack => Operand 2
      • Evaluate value using both operands and element (Operator) => value
      • Push the value to Stack
  • Pop the element of Stack => Final result


Example
String postfix = "2 3 1 * + 9 -"

element
oprnd1
oprnd2
value
stack
2



2
3



2,3
1



2,3,1
*
3
1
3*1
2,3
+
3
2
3+2
5
9



5,9
-
5
9
5-9
-4


Java code
public static int evaluatePostfix(String postfixStr) {
  String[] postfixArr = postfixStr.split("");
  Stack<Integer> stack = new Stack<Integer>();

  for(String element : postfixArr) {
      boolean isOperator = isOperator(element);
      if(isOperator) {
         int value1 = stack.pop();
         int value2 = stack.pop();
         int value = calculate(value2, value1, element);
         stack.push(value);
      else {
         stack.push(Integer.valueOf(element));
      }
  }

  return stack.pop();
}

private static int calculate(int a, int b, String operator){
  int result = 0;
  if("+".equals(operator)) {
    result = (a+b);
  else if("-".equals(operator)) {
    result = (a-b);
  else if("*".equals(operator)) {
    result = (a*b);
  else if("/".equals(operator)) {
    result = (a/b);
  
  return result;
}

private static boolean isOperator(String element) {
  if("+".equals(element) || "-".equals(element) 
         || "/".equals(element) || "*".equals(element)) {
     return true;
  }
  return false;
}

Saturday, 7 May 2016

What will happen if you try to add / remove from the Read-only collection ?


If you perform add or remove operation on a read-only collection, it will throw  UnSupportedOperationException.

How to make Collections Read-only?


Use following static methods :
  • Collections.unmodifiableCollection(Collection coll)
  • Collections.unmodifiableMap(Map map)
  • Collections.unmodifiableList(List list)
  • Collections.unmodifiableSet(Set set)



If you perform add or remove operation on a read-only collection, it will throw  UnSupportedOperationException.

Friday, 6 May 2016

What are the similarities between HashSet and TreeSet ?



  • Unique elements
  • Not Thread-safe
  • uses shallow copy by clone() method
  • Fail-Fast iterator
    • throws ConcurrentModificationException if it is modified after iterator creation

HashSet vs. TreeSet


ORDER

  • HashSet stores in random order.
  • TreeSet stores in natural order.


NULL VALUES

  • HashSet allows null
  • TreeSet will throw NullPointerException if you store null object


SPEED

  • HashSet is much faster than TreeSet


PERFORMANCE

  • HashSet has constant time performance for basic operation
    (add / remove / contains / size)
  • TreeSet has log(n) time cost for basic operation


FUNCTIONALITY

  • TreeSet is more rich than HashSet - pollFirst(), pollLast(), first(), last(), ceiling(), lower() methods


Wednesday, 4 May 2016

What are the similarities between HashSet and TreeSet ?


  • stores Unique elements
  • Not synchronized / Thread-safe (Must be explicit)
  • clone() makes shallow copies
  • Fail-Fast (If modified during iteration, throws ConcurrentModificationException)


ArrayList vs. HashMap


  • ArrayList implements List interface
  • HashMap implements Map interface
  • ArrayList stores items
  • HashMap stores key / value pairs
  • ArrayList maintains order of items
  • HashMap doesn't guarantee any order
  • ArrayList allows duplicate items
  • HashMap doesn't allows duplicate keys but allows duplicate values
  • ArrayList increases its size by 50% while resizing
  • HashMap increases its size by 100% while resizing (It also uses Load factor)


What are core interfaces and classes in Java Collection ?


Core classes and interfaces

Monday, 2 May 2016

What is concurrence level of ConcurrentHashMap in Java?


ConcurrentHashMap achieves its scalability and thread-safety by partitioning actual map into number of sectionsThis partitioning is achieved using concurrency level. 

It is optional parameter of ConcurrentHashMap constructor and it's default value is 16.

The table is internally partitioned to try to permit the indicated number of concurrent updates without contention.

Why ConcurrentHashMap doesn't allow null keys and null values ?


Reason #1. Purpose of null key
 If map.get(key) returns null, you can't detect whether the key explicitly maps to null or the key isn't mapped.

Reason #2. Ambiguities
In the ConcurrentHashMap implementation, map can be changed in between.

If it supports null key, in below code key k may be deleted in between get and containsKey calls and code will return null instead of KeyNotPresentException (expected)


if (map.containsKey(k)) {
     return map.get(k);
else {
     throw new KeyNotPresentException();
}

Monday, 25 April 2016

fail-fast vs. fail-safe iterators


fail-fast vs. fail-safe 
iterators
  • fail-fast is the property of all the collection classes in java.util package
  • fail-safe is the property of all the collection classes in java.util.concurrent are fail-safe

Advantage of fail-safe

Fail-safe works with the clone of the underlying collection so, not affected by any modification in the collection
Fail-fast iterators throw a ConcurrentModificationException, while fail-safe iterator never throws such an exception.

How to make a List read only ?


To make a List (ArrayList, Vector, LinkedList) read only, Use :

Collections.unmodifiableList(list)
It returns a new list.

If a user tries to perform add operation on the new list, it will throw :
UnSupportedOperationException

Choosing the right collection


Scenarios to choose the collection

Q. Which is faster to iterate LinkedHashSet or LinkedList ?
LinkedList

Q. Arrange in the order of speed - HashMap, HashTable, Collections.synchronizedMap, concurrentHashmap 

HashMap is fastest, then - ConcurrentHashMap, Collections.synchronizedMap, HashTable


Q. Scenario : You need to insert huge amount of objects and randomly delete them one by one. Which Collection data structure is best ?
LinkedList


Choosing right collection to use

Best general purpose implementations are : ArrayList, LinkedHashMap, and LinkedHashSet (marked below as " ")
Their overall performance is better, and you should use them unless you need a special feature like, ordering or sorting.
"Ordering" refers to the order of items returned by an Iterator.
"Sorting" refers to sorting items according to Comparable or Comparator.

Set (No duplicates)
  HashSet    |   LinkedHashSet *   |    TreeSet

List (Duplicate allowed)
  ArrayList *  |    LinkedList
  Vector          |    Stack

Map (No duplicate keys)
  HashMap   |   LinkedHashMap *   |   TreeMap
  Hashtable  |   Properties


Principal features of special implementations
  • HashMap has slightly better performance than LinkedHashMap, but its iteration order is undefined.
  • HashSet has slightly better performance than LinkedHashSet, but its iteration order is undefined.
  • TreeSet and TreeMap are ordered and sorted, but slow.
  • LinkedList has fast adding to the start of the list, and fast deletion from the interior via iteration.


Iteration order
  • HashSet - undefined
  • HashMap - undefined
  • LinkedHashSet - insertion order
  • LinkedHashMap - insertion order of keys (by default), or 'access order'
  • ArrayList - insertion order
  • LinkedList - insertion order
  • TreeSet - ascending order, according to Comparable / Comparator
  • TreeMap - ascending order of keys, according to Comparable / Comparator


Some more
  • For LinkedHashSet and LinkedHashMap, the re-insertion of an item does not affect insertion order.
  • For LinkedHashMap, 'access order' is from the least recent access to the most recent access. In this context, only calls to get,put, and putAll constitute an access, and only calls to these methods affect access order.
  • While being used in a Map or Set, these items must not change state (hence, it is recommended that these items be immutable objects) : 
          1. keys of a Map
          2. items in a Set

How to check an array of values with another array ?


Scenario
I have two arrays and I want to check, if the values of second array are present in the first array.

Solution
First, convert arrays into arrayList, then use containsAll method to check if all elements of second array are present in first array.

Example
Integer[] array1 = { 1,2,3 };
Integer[] array2 = { 2,3 };

List list1 = Arrays.asList(array1);
List list2 = Arrays.asList(array2);

if(list1.containsAll(list2)) {
  System.out.println("Yo Yo ! They are there !");
}

How to find the minimum and maximum number in List or Array ?


To get the minimum or maximum value from the list or array, we can use methods :
  • Collections.min()
  • Collections.max()

Example
Integer[ ] numbers = { 8, 2, 6, 7, 0, 1, 4, 9, 5, 3 };
List list = Arrays.asList(numbers);

int min = (int) Collections.min(list);
int max = (int) Collections.max(list);