Java set: HashSet, ArrayList, and hashsetarraylist
Set sets are unordered and repeatable. List sets are ordered and repeatable.
Java set: this problem has been mentioned in the HashSet, hashCode, and equals blogs, but the explanation is still unclear.
Let's look at a small example:
Package mark. zhang;
Import java. util. ArrayList;
Import java. util. HashSet;
Public class Test {
Public static void main (String [] args ){
ArrayList <Integer> loadsList = new ArrayList <Integer> ();
LoadsList. add (1 );
LoadsList. add (2 );
LoadsList. add (0 );
LoadsList. add (3 );
LoadsList. add (2 );
LoadsList. add (1 );
LoadsList. add (3 );
LoadsList. add (5 );
LoadsList. add (0 );
System. out. println ("the arrayList:" + loadsList );
HashSet <Integer> loadsSet = new HashSet <Integer> ();
LoadsSet. add (1 );
LoadsSet. add (2 );
LoadsSet. add (0 );
LoadsSet. add (3 );
LoadsSet. add (2 );
LoadsSet. add (1 );
LoadsSet. add (3 );
LoadsSet. add (5 );
LoadsSet. add (0 );
System. out. println ("the hashSet:" + loadsSet );
}
}
The code is very simple. Use ArrayList and HashSet to load Integer data, and then print the content of the set.
The elements in the List are loaded in the order of adding and contain repeated elements. This is the meaning of the order that can be repeated.
The elements in the Set are not loaded in the add order, and there are no repeated elements in it. This means that disorder cannot be repeated.
In other words,OrderedNot in alphabetical order or number size,RepeatedEquals between elements is true.
Select Integer here because it overwrites the equals method.
So let's think about the question: how to remove the repeated elements in the List? Reference code:
Package mark. zhang;
Import java. util. ArrayList;
Import java. util. HashSet;
Import java. util. Iterator;
Import java. util. List;
Public class Test {
Public static void main (String [] args ){
ArrayList <Integer> loadsList = new ArrayList <Integer> ();
LoadsList. add (1 );
LoadsList. add (2 );
LoadsList. add (0 );
LoadsList. add (3 );
LoadsList. add (2 );
LoadsList. add (1 );
LoadsList. add (3 );
LoadsList. add (5 );
LoadsList. add (0 );
System. out. println ("remove before --- the arrayList:" + loadsList );
// Remove the repeated element
// RmRepeatedElement (loadsList );
RmRepeadtedElementByOrder (loadsList );
System. out. println ("remove after --- the arrayList:" + loadsList );
}
Public static void rmRepeatedElement (List <Integer> list ){
HashSet <Integer> loadsSet = new HashSet <Integer> (list );
List. clear ();
List. addAll (loadsSet );
}
Public static void rmRepeadtedElementByOrder (List <Integer> list ){
HashSet <Integer> loadsSet = new HashSet <Integer> ();
ArrayList <Integer> loadsList = new ArrayList <Integer> ();
For (Iterator <Integer> iterator = list. iterator (); iterator. hasNext ();){
Integer element = iterator. next ();
If (loadsSet. add (element )){
LoadsList. add (element );
}
}
List. clear ();
List. addAll (loadsList );
}
}