Variables

HashSets in Java

Used to store values like an array and ensure there are no duplicates.


Syntax
HashSet<DataType> set = new HashSet<DataType>();

//adding to a set
set.add(item);

//checking for set membership, returns true if item is a member
set.contains(item);

Notes

The 'add' method will return true or false. It returns true if adding to the set was successful (i.e. no existing item), and false if unsuccessful (i.e. item already exists).


Example
HashSet<Integer> studentIDs = new HashSet<Integer>();
studentIDs.add(53480); //will be successful

if(studentIDs.contains(53480)){
  System.out.println("The student with ID " + 53480 + " exists.");
}

See Also
Documentation

HashSet

Add to Slack

< HashMaps   |   If Statement >

© 2019 SyntaxDB. All Rights Reserved.