Saturday, September 21, 2019

Java hashCode() and equals() – Contract, rules and best practices

1. Contract b/w them
2. Special Attention When Using in ORM

Collection Interview Questions (With Java 8 Enhancements) - Part 4 Map Interface

1. What are IdentityHashMap and WeakHashMap?
2. Explain ConcurrentHashMap? How it works?
3. How hashmap works?
4. How to design a good key for hashmap?
5. When to use HashMap or TreeMap?
6. Difference between HashMap and HashTable?
7. Difference between HashMap and ConcurrentHashMap
8. Difference between ConcurrentHashMap and Collections.synchronizedMap( HashMap )
9. Difference between HashTable and Collections.synchronized(HashMap)
So far you must have got the core idea of the similarities between them. Both are synchronized version of collection. Both have synchronized methods inside class. Both are blocking in nature i.e. multiple threads will need to wait for getting the lock on instance before putting/getting anything out of it.

So what is the difference. Well, NO major difference for above said reasons. Performance is also same for both collections.

Only thing which separates them is the fact HashTable is legacy class promoted into collection framework. It got its own extra features like enumerators.

10. How HashMap works in Java
11. [Update] HashMap improvements in Java 8
As part of the work for JEP 180, there is a performance improvement for HashMap objects where there are lots of collisions in the keys by using balanced trees rather than linked lists to store map entries. The principal idea is that once the number of items in a hash bucket grows beyond a certain threshold, that bucket will switch from using a linked list of entries to a balanced tree. In the case of high hash collisions, this will improve worst-case performance from O(n) to O(log n).

Basically when a bucket becomes too big (currently: TREEIFY_THRESHOLD = 8), HashMap dynamically replaces it with an ad-hoc implementation of the treemap. This way rather than having pessimistic O(n) we get much better O(log n).

Bins (elements or nodes) of TreeNodes may be traversed and used like any others, but additionally support faster lookup when overpopulated. However, since the vast majority of bins in normal use are not overpopulated, checking for the existence of tree bins may be delayed in the course of table methods.

Tree bins (i.e., bins whose elements are all TreeNodes) are ordered primarily by hashCode, but in the case of ties, if two elements are of the same “class C implements Comparable<C>“, type then their compareTo() method is used for ordering.

Because TreeNodes are about twice the size of regular nodes, we use them only when bins contain enough nodes. And when they become too small (due to removal or resizing) they are converted back to plain bins (currently: UNTREEIFY_THRESHOLD = 6). In usages with well-distributed user hashCodes, tree bins are rarely used.


Collection Interview Questions (With Java 8 Enhancements) - Part 3 Set Interface


1. Set Interface - Specialty & Implementations ?

Set is a unique collections of objects.It does not store duplicate objects.

Implementations :  EnumSet, HashSet, LinkedHashSet, TreeSet.

HashSet , backed by a hash table (actually a HashMap instance), is the best performing implementation, but it does not maintain order.
TreeSet is backed by red-black tree and store elements in sorted order.It is slower than HashSet.
LinkedHashSet is backed by HashTable with LinkedList running through it, so it also maintains the order of insertion.

2. Collection operation

Set<String> set =people.stream().filter(x -> x!=null).collect(Collectors.toCollection(TreeSet::new));

3. Can Set Store null values?
You can add null value, but while accessing it will give you Null Pointer Exception. 

Set<String> a1 = new HashSet<>();
Set<String> b1 = new TreeSet<>();
a1.add(null);
b1.add(null);
System.out.println(a1);
System.out.println(b1);

Output :
Exception in thread "main" java.lang.NullPointerException

4. How HashSet store elements?

You must know that HashMap store key-value pairs, with one condition i.e. keys will be unique. HashSet uses Map’s this feature to ensure uniqueness of elements. In HashSet class, a map declaration is as below:
private transient HashMap<E,Object> map;

//This is added as value for each key
private static final Object PRESENT = new Object();
So when you store a element in HashSet, it stores the element as key in map and “PRESENT” object as value. (See declaration above).
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}

5. Can a null element added to a TreeSet or HashSet?

As you see, There is no null check in add() method in previous question. And HashMap also allows one null key, so one “null” is allowed in HashSet.

TreeSet uses the same concept as HashSet for internal logic, but uses NavigableMap for storing the elements.

private transient NavigableMap<E,Object> m;

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
NavigableMap is subtype of SortedMap which does not allow null keys. So essentially, TreeSet also does not support null keys. It will throw NullPointerException if you try to add null element in TreeSet.


Collection Interview Questions (With Java 8 Enhancements) - Part 2 List Interface

1. List Interface - Specialty & implementations.

List is an Ordered collection of Objects.It can have duplicates as well. In addition to the methods available from collection interface, it also supports following operations :

  • positional access - get,set,remove,add,addall.. etc
  • search - indexOf, lastIndexOf
  • iteration - listIterator
  • range view- sublist
Implementations - ArrayList(better performing),LinkedList

Most of the polymorphic algorithms in Collections class supports list.Algorithms like - sort,reverse,shuffle,rotate,binarySearch etc.


polymorphic algorithms : In general, an algorithm is called polymorphic if it can achieve the same functionality using different data structures

2. How to convert an array of String to arraylist?

Arrays.asList(1,2,3);

3. Do List maintain Insertion Order?

Yes. By Definition, Lists are ordered collection of objects.So insertion order is maintained by default.

4. Collection operation

List<String> list = people.stream()
.map(Person::getName)
.collect(Collectors.toList());

4. Can List Store null values?


Yes. 

List<String> a = new ArrayList<>();
  List<String> b = new LinkedList<>();

  System.out.println(a);
  System.out.println(b);

Output:

[null] 
[null]
5. Difference between Vector and ArrayList?
6. Difference between ArrayList and LinkedList?
7. 

Collection Interview Questions (With Java 8 Enhancements) - Part 1

1. Collections and its need?

A collection represents a group of Objects. Prior to JDK1.2 there was no common interface/API to work on group of Objects. Only Vectors and HashTable was there to do some operations, but again there was no consistency between them.So the Java Organization decided to make a commonn interface to solve this problem and it came to know as Collection.

2. Collection Hierarchy



The Collection interface has mainly two sections :

  • 2.1 Collection
    1. Set
    2. List
    3. Queue

  • 2.2 Map
    1. SortedMap
    2. ConcurrentMap



2. The Iterator Interface

The Iterator interface contains iterator() method which is used to obtain iterator on collections.Along with iterator(), it also has forEach(Consumer<? super T> action) and spliterator() method.

3. Collection Interface

The Collection interface contains methods which are common for all the collections like :
add(E e), addAll(Collection<? extends E> ), remove(Object o), removeAll(Collection<?> c), stream(), parallelStream(), contains(Object o) , containsAll(Collection<?> c) etc.

These methods are available for all the sub-interfaces of collection interface.

4.  Why Collection interface does not extend Cloneable and Serializable interface?

Cloneable and Serializable are marker interfaces, which implies that implementing them has a specific meaning and functionality, which in turn is not required to be by default available for all the collections.
So simply, there is no need for collection to implement or extend these interfaces. There are specific collection implementations which implement them as per their specifications.

5.  Why Map interface does not extend Collection interface?

Simply because they are incompatible.

6. What is difference between fail-fast and fail-safe?

7. Difference between Iterator and ListIterator?

8. How to make a collection read only?
Use following methods:

Collections.unmodifiableList(list);
Collections.unmodifiableSet(set);
Collections.unmodifiableMap(map);
These methods takes collection parameter and return a new read-only collection with same elements as in original collection.


9. How to make a collection thread safe?
Use below methods:

Collections.synchronizedList(list);
Collections.synchronizedSet(set);
Collections.synchronizedMap(map);

10. What is BlockingQueue?

11. What is Queue and Stack, list down their differences?
A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations.
Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner.

Stack is also a form of Queue but one difference, it is LIFO (last-in-first-out).

Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll(). Also note that Stack and Vector are both synchronized.

Usage: Use a queue if you want to process a stream of incoming items in the order that they are received.Good for work lists and handling requests.
Use a stack if you want to push and pop from the top of the stack only. Good for recursive algorithms.

12. What is Comparable and Comparator interface?

13. What are Collections and Arrays classes?

14.  Impact of random/fixed hashcode() value for key
The impact of both cases (fixed hashcode or random hashcode for keys) will have same result and that is “unexpected behavior“. The very basic need of hashcode in HashMap is to identify the bucket location where to put the key-value pair, and from where it has to be retrieved.

If the hashcode of key object changes every time, the exact location of key-value pair will be calculated different, every time. This way, one object stored in HashMap will be lost forever and there will be very minimum possibility to get it back from map.

For this same reason, key are suggested to be immutable, so that they return a unique and same hashcode each time requested on same key object.

15. 

Thursday, August 28, 2014

CODE CHEF: October Challenge 2013 "Maxim and Dividers"

Hello Readers,

Today i am posting the solution of a "CODECHEF" problem. The problem was asked in the CODE CHEF: October Challenge 2013, known as  "Maxim and Dividers".
Here goes the Problem Statement.

Problem Statement

    Maxim likes dividers of the numbers. Also Maxim is fond of lucky numbers of small elephant from Lviv city.

If you remember, lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 477444 are lucky, 517467 — aren't.

Now Maxim is interested in the next information: what is the number of the integer positive dividers of number n, which are overlucky.

We call number overlucky if it is possible to remove some, but not all, digits and during bonding the remaining digits we will receive a lucky number. For example, number 72344 — overlucky, because it is possible to remove digits 2 and 3, and get number 744, which is lucky. Number 223 isn't overlucky.

Input

    The first line of the input contains an integer T denoting the number of test cases. The description of Ttest cases follows. Single line of each test case contains an integer n.

Output

    For each test case on different lines print the answer to the problem.

Constraints

  • 1 ≤ T ≤ 10
  • 1 ≤ n ≤ 10^9

Example

Input:
10
1
2
3
4
5
6
7
8
9
10

Output:
0
0
0
1
0
0
1
1
0
0




First Try it yourself...

Here is my solution in C for the above Problem:


#include<stdio.h>
#include<stdlib.h>
 
 int checkoverlucky(int i)
 {
   int k;
   
   while(i>0)
   {
   if(i%10==4||i%10==7)
   return 1;
   i=i/10;
   }
   return 0;
 }
  
int main()
{
int T,count=0,i;
int k=0;
long int n;


scanf("%d",&T);
if(T<1||T>10)
{
printf("Error in T");
exit(0);
}

while(k++<T)
{
i=4;
count=0;
   scanf("%ld",&n);
   if(n<1||n>1000000000)
   {
   printf("Error in n");
   exit(0);
   }
   while(i<=n)
   {
   if(n%i==0)
   if(checkoverlucky(i))
   {
   count++;
   }

            i++;
   }
   printf("%d \n",count);



}

return 0;
} 


Any suggestions are most welcome.. :) 

Viva La Raza
Sid 




Wednesday, June 18, 2014

Binary Representation Of A Number using recursion

The code follows:

#include<stdio.h>

int convertIntoBinary(int n)
{
    if(n>1)
        convertIntoBinary(n/2);

    printf("%d",n%2);
}

int main()
{
    convertIntoBinary(50);
    return 0;
}


Viva La Raza
Sid

The Inspiration Of the above article has been taken from: geeksforgeeks.org