Java uses ArrayList instead of arrays. Hmm For people with a lot of knowledge
I want to have a value without duplication
List<String> list = new ArrayList<String>();
~ Various processing ~
String itemNo = get〇〇
if(list.contains(itemNo)){//Do not duplicate values
list.add(itemNo);
}
Set is a collection with no duplicate elements Equals is used to prevent more than one instance of the same value.
By the way, the name Set is the English version of "set" in set theory (probably). Since the set does not allow duplicate elements (set of natural numbers, etc.)
I want to have a value without duplication
Set<String> set = new HashSet<String>();
~ Various processing ~
String itemNo = get〇〇
//↓ Deduplication is equals()No need to describe because set will do it using
//if(list.contains(itemNo)){//Do not duplicate values
set.add(itemNo);
//}
Easy to write & easy to read & easy to understand with few descriptions In the first place, it can be made clear that there is no duplication by using Set.
Actual measurement
measurement
List<Integer> list = new ArrayList<>();
Long start = System.nanoTime();
for(int i=0;i<100;i++){
for(int j=0;j<100;j++){
Integer num= i+j;
if(!list.contains(num)){
list.add(num);
}
}
}
Long end = System.nanoTime();
System.out.println("list time:"+ String.valueOf(end - start));
System.out.println(list);
Set<Integer> set = new HashSet<>();
Long start2 = System.nanoTime();
for(int i=0;i<100;i++){
for(int j=0;j<100;j++){
Integer num= i+j;
set.add(num);
}
}
Long end2 = System.nanoTime();
System.out.println("set time :"+String.valueOf(end2 - start2));
System.out.println(set);
list time:10748381 [0, 1, 2, 3, 4, 5 ~ Omitted ~ set time :5471075 [0, 1, 2, 3, 4, 5 ~ Omitted ~ // * It happens to be in descending order, but the order is not guaranteed.
The difference was nearly double. I verified it several times, but the difference is about 1.2 to 3 times, and Set is faster. However, what I want to say here is not to use it for speeding up, You don't have to worry about performance degradation and don't use Set.
Recommended Posts