Set
Set(์งํฉ)์ ํน์ง
- ์ค๋ณต์ด ์๋ค
- ์์๊ฐ ์๋ค
HashSet
import java.util.Arrays;
import java.util.HashSet;
public class hashset {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>(Arrays.asList("H", "e", "l", "l", "o"));
System.out.println(set); //[e, H, l, o]
}
}
๊ต์งํฉ, ํฉ์งํฉ, ์ฐจ์งํฉ
๊ต์งํฉ
// ๋ณต์ฌ๋ณธ ๋ง๋ค์ด์ ์ํ
HashSet<Integer> intersection = new HashSet<>(s1);
intersection.retainAll(s2);
System.out.println(intersection)
// [4, 5, 6]
ํฉ์งํฉ
HashSet<Integer> union = new HashSet<>(s1);
union.addAll(s2);
System.out.println(union)
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
์ฐจ์งํฉ
HashSet<Integer> substract = new HashSet<>(s1);
substract.removeAll(s2);
System.out.println(substract);
// [1, 2, 3]
์งํฉ ๊ด๋ จ ๋ฉ์๋
add
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Jump");
set.add("To");
set.add("Java");
System.out.println(set); // [Java, To, Jump] ์ถ๋ ฅ
}
}
addAll
import java.util.Arrays;
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Jump");
set.addAll(Arrays.asList("To", "Java"));
System.out.println(set); // [Java, To, Jump] ์ถ๋ ฅ
}
}
remove
import java.util.Arrays;
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>(Arrays.asList("Jump", "To", "Java"));
set.remove("To");
System.out.println(set); // [Java, Jump] ์ถ๋ ฅ
}
}
๋๊ธ