# URGENT: Checking An Array For The Existance Of A Value

Alan Jackson
Greenhorn
Posts: 26
Help!

Im really pressed for time, and need to loop round an int array to see if any of the values appears more than once.

For example, I need to check that the number 5 is in element 0 only. Can anyone help?

Im appreciative of all assistance!

Mani Ram
Ranch Hand
Posts: 1140
Add the elements of this array into a Set (using wrapper classes). If the add() method returns true, the added element is not a duplicate, else, it is a duplicate.

Not sure whether this is the best way to do, but it works.

Sameera Abeysinghe
Ranch Hand
Posts: 104
Hi
Just type the below program and run it
----------------------------------------------------
class B{
int aa=5;
int [] a=new int[]{1,5,3,4,5,6,7,8,9,5};
int b;
void m(){
for(int x=0;x<a.length;x++){
System.out.println("The "+a[x]+" Element is "+a[x]);
if(a[x]==aa){
b+=1;
}
}
System.out.println("Integer 5 "+b+" times");
}
}

class A{
public static void main(String [] a){
B b=new B();
b.m();
}
}
------------------------------------------------
Insert deferent values to the array
Assign the value you want to find to variable �aa�

fred rosenberger
lowercase baba
Bartender
Posts: 12203
35
not sure what your requirements are, but you could do it this way... if you're trying to find out if there are NO DUPLICATES in the array, you could do this

in other words, start at element 0. see if any element 1 - end match. if so, you can quit. if not...
start at element 1. see if it matches any element 2-end... etc.

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24212
35
Mani's solution is ok, but requires you to allocate an object for every element of the int array; Fred's is a bit brute-force as it has performance proportional to the square of the size of the array. A third possibility would be to sort the array (in time N ln N) and then scan through it looking for adjacent equal elements.

Anandh Ramesh
Ranch Hand
Posts: 61
hi

i would recommend the sorting stuff for long arrays, but this seems to be a person with little knowledge on loops. further, i believe the simplest sorting (bubble sort) also has square of the loop size for working. so, that may take even longer. moreover, sorting with lesser complexity will require more coding, which i don't think we can expect from a guy new to java. i guess the brute force comparison will work best for our guy here. though elementary, it's effective.

All the Best,
Anandh