Full Transcript

Set Notes ========= A Set is an interface that extends a Collection. It is important to know that it is NOT a List. The two implementing classes that uses Set that we will be focusing on is the HashSet and the TreeSet. A Set is a collection that contains no duplicate elements. The HashSet holds all...

Set Notes ========= A Set is an interface that extends a Collection. It is important to know that it is NOT a List. The two implementing classes that uses Set that we will be focusing on is the HashSet and the TreeSet. A Set is a collection that contains no duplicate elements. The HashSet holds all values in the order of the hash value, a value that is unique to every element created. The TreeSet holds all values in the order of the Comparable the element is created under. Create a file called ExampleSets and write the following: **import** java.util.Set; **import** java.util.TreeSet; **import** java.util.HashSet; **import** java.util.\*; **import** **static** java.lang.System.\*; **public** **class** ExampleSets { **public** **static** **void** main(String args\[\]) { TreeSet \ set = **new** TreeSet\(); HashSet \ names = **new** HashSet\(); Set\ words = **new** TreeSet\(); //Set\ money = new Set\(); } } Instantiating a Set ------------------- Since a Set is an interface, it has no constructor to instantiate. However HashSet and TreeSets are classes and do have constructors. The programmer can always instantiate a HashSet and a TreeSet in the normal generic way. However, if the programmer wants to create a set reference as a general set, then the programmer still must instantiate that set as either a HashSet or a TreeSet. If you uncomment the last line in the current example, you will get a compile-time error because there is no Set constructor. In this class, we will often use TreeSet because we know what the order of the Set would look like, we would use HashSet less often, but a HashSet is quicker because each element has its own identity and can be found immediately in the Set, giving it a Big O run time of O(1). A Hash Set uses a Hash table to store its value and so it goes directly to the value it is looking for. Add the following to the code set.add(43); set.add(32); set.add(35); set.add(48); set.add(43); set.add(35); set.add(4); set.add(3); **for**(**int** i=0; i\

Use Quizgecko on...
Browser
Browser