I have the following code generating 5-digit random numbers and adding them to an ArrayList. These numbers however must be unique ids.
for(int i = 0; i < myArr.length; i++) {
int id = (int) (Math.round(Math.random() * 89999) + 10000);
idArr.add(id);
}
I’m trying to work out how I could check to see if the number was already in the array before adding it but I can’t get my head around the best way to do this.
Use an
ArrayListinstead of anarray. That way you would just need to useArrayList#contains(obj)method to test whether theidis already in theArrayListor not.Or, you can just work with a
HashSet, which will work faster with itsHashSet#contains()method.