π Set νΉμ§
- μμκ° μλ€.
- μ€λ³΅λ κ°μ μ μ₯ν μ μλ€.
- μΈλ±μ€κ° μλ€.
π Set μμ±
- λΉ Set λ§λλ λ°©λ²: new HashSet()
- μ΄κΈ° μμλ₯Ό ν¬ν¨ν Set λ§λλ λ°©λ²: new HashSet(μ½λ μ
)
package lesson09;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Ex01 {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>();
System.out.println(set1);
Set<Integer> set2 = new HashSet<>(List.of(30, 30, 20, 10));
System.out.println(set2);
}
}
π μΆκ°/μμ /μμ /μ½κΈ°
| List | Set | Map |
---|
μΆκ° | add(), addAll() | add(), addAll() | put(), putAll() |
μμ | remove(), removeAll(), clear() | remove(), removeAll(), clear() | remove(), keySet().removeAll(), values().removeAll(), clear() |
μμ | set() | μμ μμ ν μΆκ° | λμΌν keyλ‘ λ€μ μΆκ° |
μ½κΈ° | get() | λ°λ³΅λ¬Έ(Iterator, ν₯μλ forλ¬Έ) μ¬μ© | get() |
- μΆκ°: add(), addAll()
- μμ : remove(), removeAll(), clear()
- μμ : μμ μμ ν μΆκ°
- μ½κΈ°: λ°λ³΅λ¬Έ(Iterator, ν₯μλ forλ¬Έ) μ¬μ©
μΈλ±μ€κ° μμΌλ―λ‘
- μΈλ±μ€λ‘ μ κ·Όνμ¬ νΉμ μμλ₯Ό μμ ν μ μλ€.
- μΈλ±μ€λ‘ μ κ·Όνμ¬ νΉμ μμλ₯Ό μ½μ μ μλ€.
- forλ¬Έμ μ¬μ©νμ§ μλλ€.
package lesson09;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class Ex01 {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>(List.of(30, 30, 20, 10));
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(3);
System.out.println(set1);
set1.addAll(set2);
System.out.println(set1);
set1.remove(1);
System.out.println(set1);
set1.removeAll(set2);
System.out.println(set1);
set1.clear();
System.out.println(set1);
System.out.println(set2);
set2.remove(30);
set2.add(40);
System.out.println(set2);
Iterator<Integer> iter = set2.iterator();
while(iter.hasNext()) {
Integer element = iter.next();
System.out.print(element + " ");
}
System.out.println();
for(Integer element : set2) {
System.out.print(element + " ");
}
}
}
π Set μΈν°νμ΄μ€ λ©μλ
λ©μλλͺ
| μ€λͺ
| λ°νκ° |
---|
retainAll(μ½λ μ
) | λ μ½λ μ
μμ κ°μ κ²λ§ λ¨κΈ΄λ€. | boolean(μ±κ³΅νμ§ μ¬λΆ) |
contains(κ°) | 리μ€νΈμ κ°μ΄ λ€μ΄μλμ§ νμΈ | boolean |
isEmpty() | 리μ€νΈκ° λΉμ΄μλμ§ νμΈ | boolean |
size() | Setμ ν¬κΈ° | int |
toString() | Setμ λͺ¨λ μμλ₯Ό [κ°, κ°...]μ λ¬Έμμ΄ ννλ‘ λ°ν | String |
References
π https://hahahoho5915.tistory.com/35