Notes for using javashashset in java-15.5 from the beginning
Next, let's take a look at what needs to be paid attention to when using hashset.
LinkedHashSet features:
(1) elements are ordered.
(2) elements are not repeated.
(3) the underlying data structure is stored according to the linked list structure.
(4) The hashcode and equals methods need to be re-created.
Example: (Let's modify the code in the previous chapter again)
Package com. ray. ch15; import java. lang. reflect. InvocationTargetException; import java. util. javashashset; import java. util. Set; public class Test
{Public static
Set
Fill (Set
Set, Class
Type) throws InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {for (int I = 0; I <10; I ++) {set. add (type. getConstructor (int. class ). newInstance (I);} return set;} public static
Void test (Set
Set, Class
Type) throws syntax, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {fill (set, type); System. out. println (set);} public static void main (String [] args) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {test (new hashset
(), TreeType. class); test (new LinkedHashSet
(), SetType. class); test (new LinkedHashSet
(), HashType. class) ;}} class SetType {private int id = 0; public int getId () {return id;} public void setId (int id) {this. id = id;} public SetType (int I) {id = I ;}@ Overridepublic String toString () {return id + "" ;}@ Overridepublic boolean equals (Object obj) {return obj instanceof SetType & (id = (SetType) obj ). id) ;}} class HashType extends SetType {public HashType (int I) {super (I) ;}@ Overridepublic int hashCode () {return getId ();}} class TreeType extends HashType implements Comparable
{Public TreeType (int I) {super (I) ;}@ Overridepublic int compareTo (TreeType o) {if (o. getId ()> getId () {// sort return-1;} else {if (o. getId () = getId () {// return 0;} else {return 1 ;}}}}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Note: The Comparable interface in TreeType is useless.
Summary: This section briefly describes the notes for using javashashset.
This chapter is here. Thank you.