220628 TIL

Yeoni·2022년 6월 28일
0

국비교육TIL

목록 보기
20/41

국비교육 20일차 Java : HashSet, Properties

  • List, Map
    - list에 넣기 add / list에서 꺼내오는 거 get, index 번호 /
    map에 넣기 put / map 에서 꺼내오는 거 get, key값

1. HashSet

1) HashSet과 LinkedHashSet의 차이점

  • HashSet
    - 출력시 저장된 순서가 유지되지 않는다.
    - 중복된 데이터를 저장할 수 없다.
    - 그러므로 Collection 내의 중복된 요소들을 저장하지 않고자 할때 많이 사용된다.

  • LinkedHashSet
    - 출력시 저장된 순서가 유지된다.
    - 중복된 데이터를 저장할 수 없다.
    - 그러므로 Collection 내의 중복된 요소들을 저장하지 않고자 할때 많이 사용된다.
    - HashSet과 사용방법은 똑같다.

2) HashSet의 사용

  • Example 클래스
public class Example {
	
	// field
	String name1;
	String name2;
	

	// 기본 생성자
	public Example() { 	}
	
	
	// 파라미터가 있는 생성자
	public Example(String name1, String name2) {
		this.name1 = name1;
		this.name2 = name2;
	}
	
	
	// method
	public void name_info() {
		System.out.println("1. 이름 : "+name1+"\n"
						 + "2. 번호 : "+name2+"\n");
	}
	
}
  • Main 클래스
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Main_Review {

	public static void main(String[] args) {
		
// 1. Example클래스의 객체만을 저장할 수 있는 HashSet 객체 exHashSet을 생성한다. 
		Set<Example> exHashSet = new HashSet<>(); 
		// HashSet<Example> exHashSet = new HashSet<>(); 도 가능
		
// 2. Example 클래스의 객체 5개를 생성하여 exHashSet(저장소)에 저장한다. 
		exHashSet.add(new Example("가_1","1")); 
		exHashSet.add(new Example("나_1","2")); 
		exHashSet.add(new Example("다_1","3")); 
		exHashSet.add(new Example("라_1","1")); 
		exHashSet.add(new Example("마_1","4")); 
		// 똑같은 데이터를 넣어주어도 new Example을 생성한 것이기 때문에
		// 둘이 다른 메모리 주소를 가지게 된다. 
		// 하지만, 둘이 같은 메모리 주소를 가지게 되는 경우에는 사용이 불가능 하다. 

// 3. exHashSet에 저장되어진 모든 Example들의 정보를 출력한다. 
		for(Example ex : exHashSet) {
			// 요소는 Example(element)
			ex.name_info();
		}
		
		System.out.println("\n--- 다른 방법 ---\n");
		
		// 또는 iterator를 사용할 수 있다. 
		Iterator<Example> it = exHashSet.iterator();
		// Set 계열은 저장된 데이터(요소)에 접근하기 위해서는
		// Iterator를 통하여 접근하여야 한다.
		// Iterator는 저장소가 아니라 
        // Collection에 저장되어진 요소를 불러오는 용도이다. 
		
		while(it.hasNext()) {
			// it.hasNext()는 it에서 현재 it가 가지고 있는 여러 Example 데이터 중 	
	        // 하나를 끄집어내서 존재하는지를 알아보는 것이다. 
            // 존재하면 true, 존재하지 않으면 false.

			Example ex = it.next();
			// ex에 저장된 값을 꺼내오게 되면 해당 데이터는 ex에 남아있지 않게 된다. 
			ex.name_info();
		}
		
		
		
		
	} // end of main
		
} // end of class

2. Properties

Properties 는 HashMap의 구버전인 Hashtable을 상속받아 구현한 것으로, Hashtable 은 키와 값(Object, Object)의 형태로 저장하는데 비해서
Properties 는 (String 키, String 밸류값)의 형태로 저장하는 단순화된 컬렉션 클래스이다. 키는 고유해야 한다. 즉, 중복을 허락하지 않는다. 중복된 값을 넣으면 마지막에 넣은 값으로 덮어씌운다.

1) Properties의 사용

import java.util.Enumeration;
import java.util.Properties;

public class Main_Review {

	public static void main(String[] args) {
		
		Properties prop = new Properties(); 	// properties 저장소
		
		prop.setProperty("naver", "https://www.naver.com/");
	    prop.setProperty("google", "https://www.google.com/");
		// 긴 주소 등을 간단하게 표현하는데 사용 
		
		String url = prop.getProperty("naver");
	    System.out.println(url);
	    // https://www.naver.com/

	    // === prop에 저장되어진 모든 value 값들을 출력하고자 한다. === 
	    // 먼저 prop에 저장되어진 key 목록을 알아와야 한다. 
	    // key 목록은 아래와 같이 하면 된다. 
	    
//	    Enumeration<?> en = prop.propertyNames(); 	
	    // for문을 쓰는 것이 아니라 다른 방법 사용한다. 
	    // 제네릭에서 <?>의 뜻은 ?는 
        // 아무거나를 뜻하는 것이므로 Object와 같은 의미이다. 
	    
	    @SuppressWarnings("unchecked") 	// 에러는 아니지만 노란줄 제거용
		Enumeration<String> en = (Enumeration<String>)prop.propertyNames(); 	
	    // Properties prop에서 키목록은 Enumeration<String>형태로 반환시켜준다. 
	    // ?를 실제 무슨 타입인지 적어주며 형변환 해준다. 
        // 왜냐하면 prop에 들어가 있는 값들이 다 String밖에 없기 때문이다. 
	    
	    while(en.hasMoreElements()) { 					
        // key가 하나하나 있나?
	    	String key = en.nextElement(); 				
            // en.nextElement() 실제로 값을 하나 끄집어 오고 있는 것
	    	System.out.println(key + " = " + prop.getProperty(key));
	    									// 해당 key에 매핑되어진 value값 출력 
	    } // end of while
		
	} // end of main
		
} // end of class
profile
이런 저런 기록들

0개의 댓글