How to check if each String in an array is unique?
I've got an application with six FXML textFields, where a user can provide six String inputs. These inputs are checked against a list of 31 names. If each String is not one of the names on the list, it's rejected.
I've gathered the Strings into an Array, and I'd like to check if they are unique (so the user cannot enter the same input more than once). But I've got no idea how to go about doing this!
What do you suggest, Java gurus?
Posted Oct 7, 2019, 11:56 PM UTC
Instead of adding them to an array, add them to a Set. When you are done adding, get the set size. If it is less than 6 you know there was duplicates (which sets won’t allow).
If OP adds the values to the set one by one, OP can also check the return value of the add method. add returns true if the set did not already contain the element, or returns false if the set already contained the element.
Thank you. I've been doing Java for almost a year and have never even heard of a Set, somehow. D'oh!
There are a lot of different Data Structures that are best in certain situations. Try to familiarize yourself with the concepts behind all of them and it will carry over to other languages as well. Learning to organize information correctly will have huge return on investment for time and code readability.
I'll say.
I've worked with Lists, Arrays, ArrayLists, Hashmaps/Maps, Queues, Stacks, and I think that's it. I haven't done Trees. But I can't believe I've never even heard of Sets. I just looked in my main training book, Java: A Beginner's Guide by Herbert Schildt, and it's not even in here!