Array of n size in Java -


this asked in interview:

to print duplicate values array.

i storing duplicate values in array b. storing them in hash set , printing hash set. reason storing them in hash set because want unique value duplicates. if have {1,2,2,1} in array should print {1,2}.

below program works fine have allocated fixed size array b (size = 100 in below program) , want on run time value should updated number of duplicates found. example: if have 10 duplicate values in array b b should become 10.

i checked lot before posting question, think done arraylist not sure how write array b.

import java.util.arrays; import java.util.hashset; import java.util.list;  public class duplicate_values_hash {      public static void main(string aa[])     {            integer a[] = {1, 2, 3, 1, 2, 4, 5, 1, 3, 8, 10, 11, 90, 8,12, 5, 4, 5, 8};         arrays.sort(a);          integer b[] = new integer[100]; // how update on runtime          int len,i,j = 0;         len = a.length;          for(i = 1; < len; i++)         {             if(a[i-1] == a[i])             {                    j = j + 1;                   b[j] = a[i];             }         }          list<integer> list = arrays.aslist(b);         hashset hs = new hashset();         hs.addall(list);         system.out.println(hs);      } } 

dynamically allocate array a size:

public static void main(string aa[]) {     integer a[] = {         1, 2, 3, 1, 2, 4, 5, 1, 3, 8, 10, 11, 90, 8, 12, 5, 4, 5, 8     };     arrays.sort(a);      integer b[] = new integer[a.length]; // how update on runtime      int len, i, j = 0;     len = a.length;      (i = 1; < len; i++) {         if (a[i - 1] == a[i]) {             b[j++] = a[i];         }     }      list<integer> list = new arraylist<integer>(arrays.aslist(b));     list.removeall(collections.singleton(null));     hashset hs = new hashset();     hs.addall(list);     system.out.println(hs);  } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -