풀스택/java
Java_ HashSet + Lotto
lsme
2022. 4. 29. 18:41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
import java.util.HashSet;
import static java.lang.System.out;
public class HashSetTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] nationArray = {"미국", "영국", "캐나다", "대한민국", "미국"};
HashSet<String> hs1 = new HashSet<String>();
HashSet<String> hs2 = new HashSet<String>();
for(String nation : nationArray) {
if(!hs1.add(nation)) {
//add : Collection 인터페이스에 정의되어 있다.
//요소추가가 성공하면 true로 반환.
hs2.add(nation); //중복값 들어감.
}
}
out.println("hs1 : " + hs1);
out.println("hs2 : " + hs2);
hs1.removeAll(hs2); //hs1에 hs2(미국)을 제거.
out.println("hs1 : " + hs1);
out.println("hs2 : " + hs2);
}
}
|
cs |
--
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
public class HashSetLotto {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Integer> hashSet = new HashSet<Integer>();
for(int i =0; hashSet.size() <6; i++) {
//size()
//Collection 인터페이스에서 제공하는 클래스
//컬렉션에 저장된 요소개수를 반환
int num = (int)(Math.random()*45) +1 ; //1~45
//컬렉션에는 객체타입만 들어갈 수 있다.
//AutoBoxing 되면서 추가
hashSet.add(num); //중복제거
}
//set은 정렬 기능 없다.
List<Integer> list = new LinkedList<Integer>(hashSet);
Collections.sort(list);
System.out.println(list);
}
}
|
cs |
--
Hashset 아닌 TreeSet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import java.util.TreeSet;
public class TreeSetLotto {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet treeSet = new TreeSet();
for(int i =0; treeSet.size() <6; i++) {
//size()
//Collection 인터페이스에서 제공하는 클래스
//컬렉션에 저장된 요소개수를 반환
int num = (int)(Math.random()*45) +1 ; //1~45
//컬렉션에는 객체타입만 들어갈 수 있다.
//AutoBoxing 되면서 추가
treeSet.add(num); //중복제거
}
System.out.println(treeSet);
}
}
|
cs |