HashSet Profile
HashSet data type is a collection, has the following three characteristics:
(1) may store data objects over
(2) Data can not be repeated in HashSet
(3) HashSet stored data are unordered
HashSet several common methods are as follows:
(1) add: add elements to the collection
(2) size: obtaining a set of length
(3) remove: Removes the element
(4) to traverse a set of set: a fetch iterator
Practical exercise
Special note: The following code contains acquired using an enhanced set of codes for loop element
package cn.test.logan.day06; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; public class HashSetDemo { public static void main(String[] args) { // construct a HashSet object HashSet <String> = hashSet new new HashSet <> (); // add data hashSet.add ( "Jack" ); hashSet.add("Jack"); hashSet.add("Tom"); hashSet.add("Alice"); hashSet.add("Grace"); // Get length int size = hashSet.size (); System.out.println(size); // remove elements hashSet.remove ( "Tom" ); System.out.println(hashSet.size()); System.out.println ( "---------------------------" ); // iterate set collections: a fetch iterator Iterator <String> Iterator = hashSet.iterator (); the while (iterator.hasNext ()) { // the hasNext () method is used to down "data pointer", and judges whether there is data String next = iterator.next () ; // Next () is to take the current data on the "data pointer" System.out.println (Next); } System.out.println ( "---------------------------" ); // enhanced for loop (inside the package using an iterator ) for (String tmp: hashSet) { System.out.println(tmp); } System.out.println ( "---------------------------" ); // array may also be used to enhance the operation for loop int [ ] = ARR new new int [] {2,4,5,6,7 }; for ( int TMP1: ARR) { System.out.println(tmp1); } System.out.println ( "---------------------------" ); // the ArrayList loop may be used for enhanced ArrayList <Integer> = the arrayList new new the ArrayList <Integer> (); arrayList.add(10); arrayList.add(20); arrayList.add(30); for(int tmp2:arrayList) { System.out.println(tmp2); } } }
HashSet Profile
[HashSet jiǎnjiè]
HashSet Profile