Collection(2) : Set, Map, Iterator, Stack&Queue
Collection FrameWork
컬렉션 프레임워크는 데이터 군을 저장하는 클래스들을 표준화한 설계다.
컬렉션 : 다수의 데이터(=데이터 그룹) / 프레임워크 : 표준화된 프로그래밍 방식
다수의 데이터를 다루는 데 필요한 다양하고 편리한 클래스를 제공한다.
List | 순서가 있고, 데이터 중복을 허용한다. (ex)데이터베이스 |
Set | 순서가 없고, 데이터 중복을 허용하지 않는다. |
Map | 순서가 없고, 데이터(value) 중복을 허용하나 key는 중복을 허용하지 않는다. |
Set 인터페이스
순서가 없기 때문에 같은 데이터를 저장할 경우 정확도가 떨어지므로 데이터 중복을 허용하지 않는다.
List의 중복 데이터를 제거하기 위해 사용된다.
구현된 클래스
1) TreeSet : Red-Black tree라는 자료구조의 형태로 데이터를 저장한다.
정렬, 검색, 범위검색에 매우 효율적이다.
2) HashSet*
Set의 메서드
boolean add(Object o)* : 새로운 객체를 저장한다.
boolean remove(Object o) : 지정된 객체를 삭제한다. 성공하면 true, 실패하면 false.
int size()* : 저장된 객체의 수를 반환한다.
boolean isEmpty() : Set이 비어 있는지 알려 준다.
TreeSet의 메서드
범위 검색이나 정렬 등에 특화된 만큼, 관련된 메서드가 있다.
SortedSet headSet(Object toElement) : 지정된 객체보다 작은 값의 객체들을 반환한다.
SortedSet tailSet(Object from Element) : 지정된 객체보다 큰 값의 객체들을 반환한다.
SortedSet subSet(Object fromElement, Object toElement) : 범위 검색의 결과를 반환한다. 단, 끝 범위는 포함하지 않는다.
HashSet 예시
package day29;
import java.util.*;
public class MainClass8 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("red");
list.add("red");
list.add("red");
list.add("red");
list.add("red");
for(Object obj:list) {
System.out.println("ArrayList:"+obj); //red 5번 출력
}
HashSet set = new HashSet();
set.add("blue");
set.add("blue");
set.add("blue");
set.add("blue");
set.add("blue");
for(Object obj:set) {
System.out.println("HashSet:"+obj); //blue 1번 출력
}
}
}
TreeSet 예시
package day29;
import java.util.*;
public class MainClass10 {
public static void main(String[] args) {
TreeSet set = new TreeSet();
for(int i=0; i<10; i++) {
int score = (int)(Math.random()*101);
set.add(score);
}
Iterator it = set.iterator();
while(it.hasNext()) {
System.out.print(it.next()+" ");
}
System.out.println();
System.out.println("<60점 이하>");
System.out.println(set.headSet(60));
System.out.println("<60점 이상>");
System.out.println(set.tailSet(60));
}
}
package day29;
import java.util.*;
public class MainClass11 {
public static void main(String[] args) {
String[] data = {"aaa","avbc","adf","avv","aKK",
"bbb","bdf","bDg","bsd","bdd",
"ccc","cfd","chj","cdD","cat",
"ddd","def","dim","dev","dfee"};
TreeSet set = new TreeSet();
for(String s:data) {
set.add(s);
}
System.out.println("<데이터 출력~>");
for(Object obj:set) {
System.out.print(obj+" ");
}
System.out.println();
System.out.println(set.subSet("b", "d"));//b와 d 사이에 있는것
}
}
Map 인터페이스
키(key)와 값(value)의 쌍으로 저장된다.
값의 중복은 허용되나 값의 중복은 허용되지 않는다.
만약 기존에 저장된 데이터와 중복된 키key와 값value을 저장하면 기존의 값은 새로 저장된 값으로 대체된다.
웹에서 사용되는 대부분의 클래스가 Map 클래스이다.
→ request, response, session(서버저장), cookie(브라우저 저장),..
그 외에 myBatis(데이터베이스 관리), Spring(클래스를 모아서 관리)에서 사용함.
구현된 클래스
1) HashTable 거의 사용되지 않음
2) HashMap*** : HashTable의 단점을 보완함. 키와 값을 (Object, Object)의 형태로 저장한다.
→ 웹소켓에 사용된다.
3) Properties : HashTable을 상속받아 구현함. 키와 값을 (String, String) 형태로 저장한다.
→ 주로 애플리케이션의 환경설정과 관련된 속성을 저장하거나 데이터를 파일로부터 읽고 쓰는 기능을 제공한다.
Map의 메서드
boolean containsKey(Object key) : 지정된 key가 포함되어 있는지 알려 준다.
Object put(Object key, Object value)* : value객체를 key객체에 연결하여 저장한다.
Object get(Object key)* : 지정한 key 객체에 대응하는 value 객체를 찾아 반환한다.
Properties 의 메서드
void load(InputStream inStream) : 지정된 InputStream으로부터 목록을 읽어 저장한다.
Object setProperty(String key, String value) : 지정된 키와 값을 저장한다.
String getProperty(String key) : 지정된 키의 값을 반환한다.
HashMap 예시
package day29;
import java.util.*;
class A {
public void display() {
System.out.println("A:display() call..");
}
}
class B {
public void display() {
System.out.println("B:display() call..");
}
}
class C {
public void display() {
System.out.println("C:display() call..");
}
}
//클래스 A,B,C 를 모아서 관리
class Container {
private HashMap map = new HashMap();
public Container() {
map.put("a", new A());
map.put("b", new B());
map.put("c", new C()); //factory pattern
}
//클래스 찾기
public Object getBean(String key) {
return map.get(key);
}
}
public class MainClass13 {
public static void main(String[] args) {
Container c = new Container();
System.out.println("<A클래스 요청>");
A a = (A) c.getBean("a");
a.display();
System.out.println("<B클래스 요청>");
B b = (B) c.getBean("b");
b.display();
System.out.println("<C클래스 요청>");
C cc = (C) c.getBean("c");
cc.display();
}
}
HashMap 예시2
아래와 같이 클래스 A, B, C가 있다고 하자.
각각 display()라는 같은 이름의(다르게 작동하는)메서드를 가지고 있다.
사용자가 입력한 값에 맞는 클래스의 메서드를 호출하고 싶을때, 지금까지는 아래와 같이 처리했다.
package day29_2;
import java.util.Scanner;
class A{
public void display() {System.out.println("A:display() Call..");}
}
class B{
public void display() {System.out.println("B:display() Call..");}
}
class C{
public void display() {System.out.println("C:display() Call..");}
}
public class MainClass5 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("입력(a,b,c):");
String cmd = scan.next();
if(cmd.equals("a")) {
A a = new A();
a.display();
}
else if(cmd.equals("b")) {
B b = new B();
b.display();
}
else if(cmd.equals("c")) {
C c = new C();
c.display();
}
}
}
공통된 메서드 display()만을 갖는 인터페이스 I를 선언하여 각 클래스가 I를 implements하도록 구현하면...
if문마다 매번 각 클래스의 메서드를 호출하지 않아도 된다.
package day29_2;
import java.util.Scanner;
interface I{
public void display();
}
class A implements I{
@Override
public void display() {System.out.println("A:display() Call..");}
}
class B implements I{
@Override
public void display() {System.out.println("B:display() Call..");}
}
class C implements I{
@Override
public void display() {System.out.println("C:display() Call..");}
}
public class MainClass6 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("입력(a,b,c):");
String cmd = scan.next();
I i = null;
if(cmd.equals("a")) {
i = new A();
}
else if(cmd.equals("b")) {
i = new B();
}
else if(cmd.equals("c")) {
i = new C();
}
i.display();
}
}
그리고 HashMap을 이용해서 각 cmd값에 맞는 생성자를 넣어 주고,
if문 없이 원하는 클래스의 메서드를 가져다 쓸 수 있게 됐다.
package day29_2;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
interface II{
public void display();
}
class AA implements II{
@Override
public void display() {System.out.println("AA:display() call..");}
}
class BB implements II{
@Override
public void display() {System.out.println("BB:display() call..");}
}
class CC implements II{
@Override
public void display() {System.out.println("CC:display() call..");}
}
public class MainClass7 {
public static void main(String[] args) {
Map<String,II> map = new HashMap<String,II>();
map.put("a", new AA());
map.put("b", new BB());
map.put("c", new CC());
Scanner scan = new Scanner(System.in);
System.out.print("a,b,c?: ");
String cmd = scan.next();
II i = map.get(cmd);
i.display();
}
}
Properties 예시
package day29;
import java.util.*;
import java.io.*; //얘꺼쓸려면 예외처리 꼭
public class Class14 {
public static void main(String[] args) {
//파일로 DB의 정보, 메뉴 저장, 유효성 검사
try {
Properties prop = new Properties();
prop.load(new FileInputStream("C:\\doodooProgramming\\java\\db.properties"));
System.out.println("driver:" + prop.getProperty("driver"));
System.out.println("url:" + prop.getProperty("url"));
System.out.println("username:" + prop.getProperty("username"));
System.out.println("password:" + prop.getProperty("password"));
System.out.println("maxActive:" + prop.getProperty("maxActive"));
System.out.println("maxIdle:" + prop.getProperty("maxIdle"));
System.out.println("maxWait:" + prop.getProperty("maxWait"));
} catch (Exception ex) {}
}
}
Iterator 인터페이스
컬렉션에 저장된 각 요소에 접근하는 기능을 수행한다.
컬렉션 인터페이스에서는 Iterator를 구현한 클래스의 인스턴스를 반환하는 iterator() 를 정의한다.
→ List나 Set 인터페이스를 구현하는 컬렉션은 iterator()가 각 특징에 맞게 작성되어 있다.
컬렉션 클래스에 대해 iterator()를 호출하여 Iterator를 얻은 후,
반복문(주로 while)을 이용해서 컬렉션에 저장된 요소들을 읽어올 수 있다.
Iterator의 메서드
boolean hasNext()* : 읽어 올 요소가 남아 있는지 확인한다. 있으면 true, 없으면 false 반환!
Object next()* : 다음 요소를 읽어 온다.
void remove() : next()로 읽어 온 요소를 삭제한다.
package day29;
import java.util.*;
public class MainClass6 {
public static void main(String[] args) {
ArrayList a = new ArrayList();
a.add("1");
a.add("2");
a.add("3");
a.add("4");
a.add("5");
ListIterator it = a.listIterator();
while(it.hasNext()) {
System.out.println(it.next());
}
while(it.hasNext()) {
System.out.println("Iterator재출력:"+it.next()); //출력안됨
}
for(Object obj:a) {
System.out.println("List재출력:"+obj); //여러번 출력 가능.
}
}
}
package day29;
import java.util.*;
public class MainClass5 {
public static void main(String[] args) {
// ArrayList list = new ArrayList();
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
//Iterator는 데이터를 모아서 순차적으로 접근할 수 있도록 만들어주는 라이브러리다.
//-> 표준화
//Iterator로 데이터를 모아 준다.
Iterator iter = list.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
list = new Vector();
// Vector list2 = new Vector();
list.add("11");
list.add("22");
list.add("33");
list.add("44");
list.add("55");
iter = list.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
list = new LinkedList();
// LinkedList list3 = new LinkedList();
list.add("111");
list.add("222");
list.add("333");
list.add("444");
list.add("555");
//한 개의 이름으로 여러 개를 제어 -> 인터페이스의 장점
//유지보수가 쉽고 수정이 용이하다.
iter = list.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
}
}
Map 인터페이스를 구현한 컬렉션 클래스는 iterator()를 직접 호출할 수 없다.
→key와 value를 짝지어 저장하기 때문!
→→keySet()나 entrySet()을 통해 key와 value를 따로 Set의 형태로 저장한 후 다시 iterator()를 호출해 주어야 한다.
Stack & Queue
Stack은 선입후출(Last In First Out), Queue는 선입선출(First In First Out) 구조이다.
Stack의 메서드
boolean empty() : 스택이 비었는지 알려 준다.
Object pop() : 스택의 맨 위에 있는 객체를 꺼낸다.
Object peek() : 스택의 맨 위에 있는 객체를 반환한다.(객체를 꺼내지는 않음)
Object push() : 스택에 객체를 저장한다.
Queue의 메서드
boolean add(Object o) : 지정된 객체를 큐에 추가한다.
Object remove() : 큐에서 객체를 꺼내서 반환한다. (비어 있으면 NoSuchElementException 발생!)
Object poll() : 큐에서 객체를 꺼내서 반환한다. (비어 있으면 null 반환)
Objcet peek() : 삭제 없이 객체를 읽어 온다.
package day29;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class MainClass4 {
public static void main(String[] args) {
System.out.println("<Stack 이용하기>");
Stack st = new Stack();
st.push("data1");
st.push("data2");
st.push("data3");
while(!st.isEmpty()) {
System.out.println(st.pop());
}
System.out.println("<Queue 이용하기>");
Queue q = new LinkedList();
//Stack은 일반클래스지만 Queue는 인터페이스이기 때문에 LinkedList를 통해 선언해야 한다.
q.offer("data1");
q.offer("data2");
q.offer("data3");
while(!q.isEmpty()) {
System.out.println(q.poll());
}
}
}
package day29;
public class MainClass3 {
public static void main(String[] args) {
String[] colors = new String[5];
colors[0] = "red";
colors[1] = "blue";
colors[2] = "green";
colors[3] = "yellow";
colors[4] = "black";
System.out.println("<Stack>");
for(int i=colors.length-1; i>=0; i--) {
System.out.println(colors[i]); //black, yellow, green, blue, red
}
System.out.println("<Queue>");
for(int i=0; i<colors.length; i++) {
System.out.println(colors[i]); //red, blue, green, yellow, black
}
}
}
'부트캠프(END) > Java' 카테고리의 다른 글
Generics, Annotation (0) | 2022.06.13 |
---|---|
Collection(1) : List (0) | 2022.06.10 |
java.util package, java.text.Format (0) | 2022.06.09 |