JAVA/코드

2022_10_26 연습 02 day03_10_26.src.com.ssc.set

0304호 2022. 10. 27.
package day03_10_26.src.com.ssc.set;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class SetClassCompare {
	public static void main(String[] args) {
		//문자열을 저장하는 Set인스턴스를 3개 생성
		Set<String> hashSet = new HashSet<>();
		Set<String> linkedhashSet = new LinkedHashSet<>();
		Set<String> treeSet = new TreeSet<>();
		
		hashSet.add("LG EDS");
		linkedhashSet.add("LG EDS");
		treeSet.add("LG EDS");
		
		hashSet.add("SS SDS");
		linkedhashSet.add("SS SDS");
		treeSet.add("SS SDS");
		
		hashSet.add("29");
		linkedhashSet.add("29");
		treeSet.add("29");
		
		hashSet.add("Tree");
		linkedhashSet.add("Tree");
		treeSet.add("Tree");

		hashSet.add("Grape");
		linkedhashSet.add("Grape");
		treeSet.add("Grape");
		
		hashSet.add("KB");
		linkedhashSet.add("KB");
		treeSet.add("KB");
		
		hashSet.add("KAKAO");
		linkedhashSet.add("KAKAO");
		treeSet.add("KAKAO");
		
		hashSet.add("25");
		linkedhashSet.add("25");
		treeSet.add("25");
		
		
		//출력
		//HashSet : 알수가없음
		for(String company : hashSet) {
			System.out.print(company + "\t");
		}
		System.out.println();
		
		//LinkedhashSet : 저장한 순서대로 출력
		for(String company : linkedhashSet) {
			System.out.print(company + "\t");
		}
		System.out.println();
		
		//treeSet
		for(String company : treeSet) {
			System.out.print(company + "\t");
		}
		System.out.println();
		
	}

}​
package day03_10_26.src.com.ssc.set;

import java.util.ArrayList;
import java.util.Random;
import java.util.TreeSet;

public class Lotto {
	
	public static void main(String[] args) {
		//랜덤한 숫자를 추출하기 위한 인스턴스 생성
		Random r = new Random();
		
		//ArrayList 활용
		ArrayList<Integer> al = new ArrayList<>();
		while(al.size()<6) {
			//1~45 까지의 숫자를 랜덤하게 추출
			int su = r.nextInt(45) +1;
			
			//중복검사를 해서 통과하면 add하고 통과하지 못하면 add를 수행하지 않음
			if(al.contains(su)) continue;
			
				al.add(su);
			
		}
		//출력하기 전에 정렬
		al.sort(null);
		System.out.println(al);

		
		//TreeSet은 중복된 데이터를 저장하지않고 저장된 순서를 기억합니다.
		TreeSet<Integer> treeSet = new TreeSet<>();
		
		while(treeSet.size()<6) {
			//1~45 까지의 숫자를 랜덤하게 추출
			int su = r.nextInt(45) +1;
			//TreeSet은 중복된 데이터를 저장하지 않기 때문에 검사할 필요가 없음
				treeSet.add(su);
		}
		
		for(Integer i : treeSet) {
			System.out.printf(i+"  ");
		}
		
		
		
		
	}

}

댓글