알고리즘을 풀던 중 HashSet을 사용해야 했고, HashSet이 저장 순서가 유지되지 않는다는 점으로 인해, LinkedHashSet을 사용해야했다. 이를 계기로 HashSet과 LinkedListHashSet의 사용법을 간략히 적으려고 한다.
HashSet<데이터타입> set2 = new HashSet<데이터타입>();
//HashSet<Integer> set = new HashSet<Integer>();
//HashSet<String> set2 = new HashSet<String>();
public class HashSetTest {
public static void main(String[] args) {
// Integer
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(1);
// String
HashSet<String> set2 = new HashSet<String>();
set2.add("a");
set2.add("b");
set2.add("c");
set2.add("a");
}
public class HashSetTest {
public static void main(String[] args) {
// Integer
HashSet<Integer> set = new HashSet<Integer>();
set.remove(1); //1 삭제
set.clear(); //HashSet 초기화
// String
HashSet<String> set2 = new HashSet<String>();
set2.remove("a");
set2.clear();
}
}
public class HashSetTest {
public static void main(String[] args) {
// Integer
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(1);
System.out.println("set의 크기 : " + set.size());
}
}
public class HashSetTest {
public static void main(String[] args) {
// Integer
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(1);
System.out.println("1은 있는가? : " + set.contains(1)); //출력 : 1은 있는가? true
}
}
public class HashSetTest {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
System.out.println("set의 값 : " + set); //set의 값 : [1, 2]
Iterator iter = set.iterator();
while(iter.hasNext()) {
System.out.print(iter.next() + " ");
}
System.out.println("");
}
}
public class HashSetTest {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
myHashSet.add("kiwi");
myHashSet.add("apple");
myHashSet.add("melon");
System.out.println("Set: " + myHashSet);
List<String> list = new ArrayList<>(myHashSet);
Collections.sort(al);
System.out.println("Sorted list: " + al);
}
}
HashSet<>은 저장 순서가 유지되지 않는다. 대신 LinkedList<>를 사용하면 저장순서가 유지된다.
public class Main{
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String[] strings = bf.readLine().split(" ");
int n = Integer.parseInt(strings[1]);
LinkedHashSet<String> set = new LinkedHashSet<>();
//HashSet<String> set = new HashSet<>(); 저장 순서 유지 X
for(int i=0; i<n; i++) {
set.add(bf.readLine());
}
Iterator iter = set.iterator();
for(String s : set) {
System.out.println(s);
}
}
}