HashSet์ ์ค๋ณต์ ํ์ฉํ์ง ์๋ ๋ฐ์ดํฐ ์งํฉ์ ๊ด๋ฆฌํ ๋ ์ ์ฉํ๋ค.
HashSet์ ๋ค์๊ณผ ๊ฐ์ ํน์ง์ ๊ฐ์ง ์๋ฃ๊ตฌ์กฐ์ด๋ค.
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
// HashSet ์ ์ธ
HashSet<String> fruits = new HashSet<>();
// ์์ ์ถ๊ฐ .add()
fruits.add("apple");
fruits.add("banana");
fruits.add("orange");
fruits.add("apple"); // ์ค๋ณต๋ ๊ฐ์ ์ถ๊ฐ๋์ง ์์
// HashSet ์ถ๋ ฅ
System.out.println(fruits); // ์ถ๋ ฅ ์์: [banana, orange, apple]
// ํน์ ์์ ํฌํจ ์ฌ๋ถ ํ์ธ .contains()
System.out.println("Contains apple? " + fruits.contains("apple")); // true
System.out.println("Contains mango? " + fruits.contains("mango")); // false
// ์์ ์ ๊ฑฐ .remove
fruits.remove("banana");
System.out.println("After removing banana: " + fruits); // [orange, apple]
// ์ ์ฒด ์์ ๊ฐ์ .size()
System.out.println("Size of HashSet: " + fruits.size()); // 2
// ๋ชจ๋ ์์ ์ ๊ฑฐ .clear()
fruits.clear();
System.out.println("Is HashSet empty? " + fruits.isEmpty()); // true
}
}
import java.util.HashSet;
import java.util.Arrays;
public class RemoveDuplicatesExample {
public static void main(String[] args) {
// ๋ฐฐ์ด์ ์ค๋ณต๋ ์์๋ค
Integer[] numbers = {1, 2, 3, 1, 2, 4, 5, 3};
// HashSet์ ๋ฐฐ์ด์ ์ถ๊ฐํด ์ค๋ณต ์ ๊ฑฐ
HashSet<Integer> uniqueNumbers = new HashSet<>(Arrays.asList(numbers));
// HashSet ์ถ๋ ฅ (์ค๋ณต์ด ์ ๊ฑฐ๋ ์ํ)
System.out.println(uniqueNumbers); // ์ถ๋ ฅ ์์: [1, 2, 3, 4, 5]
}
}
import java.util.HashSet;
public class IterateHashSetExample {
public static void main(String[] args) {
HashSet<String> cities = new HashSet<>();
cities.add("Seoul");
cities.add("New York");
cities.add("Tokyo");
// ํฅ์๋ for ๋ฌธ์ ์ฌ์ฉํ์ฌ HashSet ํ์
for (String city : cities) {
System.out.println(city);
}
}
}