could any one help me. i am making an app, and in the java, numbers are send to a int array and i need to check if any of the numbers in the array repeated and if there are to c
I'd write something like:
public boolean hasRepeatedNumbers(int[] a) { int[] b = new int[a.length]; System.arraycopy(a, 0, b, 0, a.length); Array.sort(b); int i; for (i = 1; i < b.length; i++) { if (b[i] == b[i-1]) return true; } return false; }
This works because we sort the array (actually a copy of the array, since we don't want to mess with the caller's original array), then detect adjacent duplicates. Since the array is sorted, all duplicates will necessarily be adjacent.
If the array is large and copying it is expensive, you can do it in place (but document the function to this effect).
If you can't sort the array, you can also build a set, then iterate through the array testing if the current value is in the set -- if it is, it's a duplicate. If not, place it into the set.
You can use Collections.frequency() method to get count of how many times a number is repeated.Depending on what you want, you can iterate over an array of Integers and check how many times each one repeated. if an items frequency is greater than 1 than it is repeating in that array. You can adapt the following code according to your needs. Note: by the way System.out.println() gives output to eclipse log cat section. it is just for demonstration.
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(new Integer(3));
nums.add(new Integer(3));
nums.add(new Integer(3));
nums.add(new Integer(2));
nums.add(new Integer(2));
nums.add(new Integer(1));
System.out.println("Number of 1's" + " " + Collections.frequency(nums, 1));
System.out.println("Number of 2's" + " " + Collections.frequency(nums, 2));
System.out.println("Number of 3's" + " " + Collections.frequency(nums, 3));
What are yuou trying to emulate it's a SET
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
Set is an interface so you can use HashSet or TreeSet to implement that interface. So you will have only 1 object of the same value even if you try to add the same.
To ensure if you have already that object (in other to fire your event / method ) you can use the function contains that return a boolean checking if that element already exist in the set.