자바 - 로또2(HashSet을 이용한 로또)
HashSet를 이용한 로또 만들기
-------------------------------
package dr03.random;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class LottoHashSet {
Set<Integer> vc;
public LottoHashSet(){
vc = new HashSet<Integer>();
this.doLotto();
this.printLotto();
}
public void doLotto(){
Random ra = new Random();
Integer ir = null;
while(vc.size()<6) {
ir = new Integer(ra.nextInt(45)+1);
// 중복값 체크, HashSet의 add() 메소드는 데이터 저장시 중복값을 허용하지 않음
vc.add(ir);
}
}
public void printLotto(){
// Collections.sort()를 이용해 정렬하기 위해 Set -> List 으로 변환
List<Integer> list = new ArrayList<Integer>(vc);
Collections.sort(list); // 오름차순으로 정렬
for(int i : list){
System.out.print(i+"\t");
}
}
public static void main(String[] args) {
new LottoHashSet();
}
}