Set
Set은 List와 달리 순서가 없다.
package oop0916;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Test04_SetMap {
public static void main(String[] args) {
// 2. Set 계열 : 순서가 없다
Set set = new HashSet();
set.add(3);
set.add(2.4);
set.add('R');
set.add("BUSAN");
set.add(new Integer(7));
System.out.println(set.size());
//cursor : 가리킬 요소가 있으면 true, 없으면 false 값 반환
//cursor를 이용해서 요소에 접근하는 경우
Iterator iter = set.iterator();
while (iter.hasNext()) { //다음 cursor가 있는지?
//cursor가 가리키는 요소 가져오기
Object obj = iter.next();
System.out.println(obj);
}//while end
}
}
객체를 가져올 때 list는 get 메소드를 이용했다. 하지만 Set에는 get 메소드가 없다. 대신 Iterator를 이용하여 값을 가져올 수 있다.
Iterator의 hasNext 메소드는 가져올 객체가 있으면 true, 없으면 false 값을 반환한다. 이를 통해 값을 출력해보니
위와 같다. 앞서 말했듯이 Set은 순서가 없기 때문에 우리가 객체를 추가한 순서대로 출력되지 않는다.
Map
Map 역시 순서가 없으며 Key와 Value로 구성되어있다. Key는 이름표, Value는 값이다.
HashMap map = new HashMap();
map.put("one", 3);
map.put("two", 2.4);
map.put("three", 'R');
map.put("four", "손흥민");
System.out.println(map.size()); //4
System.out.println(map.get("four")); //손흥민
map.put("four", "박지성");
System.out.println(map.get("four")); //박지성
※ 참고 Properties
Properties db = new Properties();
db.put("url", "http://localhost:1521");
db.put("username", "itwill");
db.put("password", "12341234");
System.out.println(db.get("url"));
System.out.println(db.get("username"));
System.out.println(db.get("password"));
연습문제
//문제) = 문자를 기준으로 문자열을 분리해서, = 앞의 문자열은 Key, = 뒤의 문자열은 Value로 구분해서
// map에 저장하고 map의 key 값들 중에서 "read.do"를 호출하면 value 값으로 net.bbs.Read 출력하시오
HashSet command = new HashSet();
command.add("list.do=net.bbs.List");
command.add("read.do=net.bbs.Read");
command.add("write.do=net.bbs.Write");
System.out.println(command.size()); //3
HashMap hm = new HashMap();
//내 풀이
Iterator cm = command.iterator();
while (cm.hasNext()) {
Object objt = cm.next();
String str = objt.toString();
String k = str.substring(0, str.indexOf("="));
String v = str.substring(str.indexOf("=")+1);
hm.put(k, v);
}//for end
//다른 풀이
//1) 커서 생성하기
Iterator cursor = command.iterator();
//2) 커서가 있을때까지 반복
while (cursor.hasNext()) {
//3) 커서가 가리키는 요소를 가져와서 문자열 형변환
Object obj = cursor.next();
String line = (String) obj; //다형성
//System.out.println(line);
//4) "=" 위치를 기준으로 문자열 분리하기
//-> split(), substring(), StringTokenizer클래스
String[] word = line.split("=");
String key = word[0]; //"=" 앞 문자열
String value = word[1]; //"=" 뒤 문자열
//System.out.println(key);
//System.out.println(value);
//5) hm에 저장하기
hm.put(key, value);
}//while end
'웹개발 교육 > Java' 카테고리의 다른 글
[37일] Java (47) - 상품 구매 및 반품 프로그램 (0) | 2022.09.19 |
---|---|
[36일] Java (46) - generic (0) | 2022.09.16 |
[36일] Java (44) - List (0) | 2022.09.16 |
[36일] Java (43) - throws (0) | 2022.09.16 |
[36일] Java (42) - Exception (0) | 2022.09.16 |