My question is how would I not allow duplicate values into an array? For example I have a program that is supposed to take five user input values that are between 10 and 100, and put them into an array. Also it is supposed to tell if the value the user is imputing currently is a duplicate to one found in the array currently. If so it is not supposed to record the value, and at the end of five inputs it is supposed to output the array with only unique values. So for example is the user input: 12, 16, 30, 30, 99, the end output would be: 12, 16, 30, 99. How would I eliminate the duplicates?
2 Answers
An easy way would consist in storing each inputs into a Set as it won't add data if already present.
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.
Note that the add method will return true if the set did not already contain the specified element which make it easier to log an error message if it does.
if(!yourSet.add(input))
System.out.println("Already exist.");
If you look at the source code of the map method of HashSet
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
You will notice that everything is stored in an HashMap, then at each add, the return value will be true if the put call returned null, which will happen if there were no previous mapping for this key.
The PRESENT object is just a dummy value to be able to use the put method properly.
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
If you really can't use a Set, here how you can achieve this :
- Define a boolean which will be a flag to mark if values are equals or not.
- Loop over all datas of the array each time you have an input.
- At each iteration set the flag to true only if data are equals.
Make sure your loop stop looping when the boolean is set to true
for(int i = 0; !flag && i < array.length; i++)- Outside the loop only add data if flag's value is false.
- Put all this in an other loop that read all user inputs until a sentinel value is entered.
2 Comments
Use a Set:
Set<Integer> aSet = new HashSet<Integer>();
aSet.add(12);
aSet.add(16);
aSet.add(30);
aSet.add(30);
aSet.add(99);
for (Integer number:aSet) {
System.err.print(number+", ");
}
System.err.println();
This will print out 12, 16, 30, 99,
Set.