+ 3

write a programme that printout the similar elements of the array?

let we have and array int [x]={1,2,3,4,5,6,7,8,9,3,6,7} then the output should be 3,6,7. i want to check out different methodology to doing this.

8th Aug 2016, 12:55 PM
Abhi Bhardwaj
Abhi Bhardwaj - avatar
6 Answers
+ 1
import java.util.HashSet; public class Program { public static void main(String[] args) { int x[] = { 1,2,3,4,5,6,7,8,9,3,6,7 }; HashSet set = new HashSet(); for(int i: x){ if(set.contains(i)){ System.out.println(i); }else{ set.add(i); } } } }
8th Aug 2016, 2:41 PM
WPimpong
WPimpong - avatar
0
import java.util.Arrays; public class Program { public static void main(String[] args) { int[] x = {1,2,3,4,5,6,7,8,9,3,6,7}; Arrays.sort(x); for (int i = 0; i < x.length; i++){ if(x[i] > x[0]) if(x[i] == x[i - 1]) System.out.println(x[i]); } } } Off the top of my head, that's what I came up with :)
8th Aug 2016, 1:22 PM
James
James - avatar
0
you don't have to use built in function like Arrays.sort(x).
8th Aug 2016, 1:26 PM
Abhi Bhardwaj
Abhi Bhardwaj - avatar
0
Never said you did, you were checking for methodology, that's the method I chose :)
8th Aug 2016, 1:27 PM
James
James - avatar
0
That's why i mention for furthee answer dude.. and nice way
8th Aug 2016, 1:29 PM
Abhi Bhardwaj
Abhi Bhardwaj - avatar
0
@WPimpong for(int i: x){ if(!set.add(i)) System.out.println(i); }
29th Dec 2016, 7:34 PM
Murmeltier
Murmeltier - avatar