The difference between Java ArrayList and HashSet
Example 1: Is there a sequence
ArrayList: sequential
HashSet: No order
HashSet particular order is neither insertion order, nor is the order of hashcode.
The following are HasetSet source portion annotation
/**
* It makes no guarantees as to the iteration order of the set;
* in particular, it does not guarantee that the order will remain constant over time.
*/
Set the iteration order is not guaranteed; rather, under different conditions, the order of elements are likely to be different
In other words, the same is inserted into the HashSet 0-9, different versions of the JVM in order to see are not the same. So when developed, can not rely on a certain order of speculation , the order itself is unstable
package collection;
import java.util.ArrayList;
import java.util.HashSet;
public class TestCollection {
public static void main(String[] args) {
ArrayList<Integer> numberList =new ArrayList<Integer>();
//List中的数据按照插入顺序存放
System.out.println("----------List----------");
System.out.println("向List 中插入 9 5 1");
numberList.add(9);
numberList.add(5);
numberList.add(1);
System.out.println("List 按照顺序存放数据:");
System.out.println(numberList);
System.out.println("----------Set----------");
HashSet<Integer> numberSet =new HashSet<Integer>();
System.out.println("向Set 中插入9 5 1");
//Set中的数据不是按照插入顺序存放
numberSet.add(9);
numberSet.add(5);
numberSet.add(1);
System.out.println("Set 不是按照顺序存放数据:");
System.out.println(numberSet);
}
}
Example 2: Can repeat
Data List can duplicate
data Set is not able to repeat
repeat criteria are:
First look hashcode is the same as
if hashcode different, then that is different from the data
if hashcode same, compare equals, if equals the same, the same data, otherwise different data
package collection;
import java.util.ArrayList;
import java.util.HashSet;
public class TestCollection {
public static void main(String[] args) {
ArrayList<Integer> numberList =new ArrayList<Integer>();
//List中的数据可以重复
System.out.println("----------List----------");
System.out.println("向List 中插入 9 9");
numberList.add(9);
numberList.add(9);
System.out.println("List 中出现两个9:");
System.out.println(numberList);
System.out.println("----------Set----------");
HashSet<Integer> numberSet =new HashSet<Integer>();
System.out.println("向Set 中插入9 9");
//Set中的数据不能重复
numberSet.add(9);
numberSet.add(9);
System.out.println("Set 中只会保留一个9:");
System.out.println(numberSet);
}
}
Exercise : non-repeating random numbers
Generating a random number between 0 and 9999. 50, the requirements can not be duplicated
Answer:
package collection;
import java.util.HashSet;
import java.util.Set;
public class TestCollection {
public static void main(String[] args) {
Set<Integer> numbers =new HashSet<>();
while(numbers.size()<50){
int i = (int) (Math.random()*10000);
numbers.add(i);
}
System.out.println("得到50个不重复随机数:");
System.out.println(numbers);
}
}