Skip to main content

Posts

Showing posts from February 2, 2019

Core Java Programming Question from Collection

Program to find the frequency string in string array (Passing String from command line arguments) package com.myconceptsonjava.practice; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Test {     public static void main(String[] args) {     Map<String, Integer> m = new HashMap<String, Integer>();     // Initialize frequency table from command line     for (String a : args) {     Integer freq = m.get(a);     m.put(a, (freq == null) ? 1 : freq + 1);     }     System.out.println(m); } } Program to find the frequency string in string array and print them in natural  sorting order (Passing String from command line arguments) package com.myconceptsonjava.practice; import java.util.ArrayList; import java.util.TreeMap; import java.util.List; import java.util.Map; public class Test {     public static void main(String[] args) {     Map<String, Integer> m = new TreeMap<String, Integer>();     // Initia

Interview question on java for Experience

Why does StringBuffer/StringBuilder not override equals or hashCode? Ans:    Actually behind this everything depends upon hashcode code value. To understand this concept lets take an example : String str1 = new String ( "chandan" ); String str2 = new String ( "chandan" ); HashMap hm = new HashMap () hm . put ( str1 , "hello" ); hm . put ( str2 , "bye" ); final hm: hm = { chandan = bye } In above code, str1 and str2 are two different String objects. It should be added in HashMap ? Answer is  NO . Because before inserting/putting value in HashMap, it internally checks and compare hashCode value of  str1 ,  str2 . Both retun same hascode value because String class override equals() and hashcode() method. So upon executing  hm.put(str2,"bye");  first key will get override with new value. Now try this : StringBuilder sb1 = new StringBuilder ( "chandan" ); StringBuilder sb2 = new StringBuilder (