Map 계열 컬렉션 클래스 살펴보기
------------------------------------------------------------
Map계열의 자료구조는 쉽게 생각해서 지하철에 비치되어 있는 물품 보관함을 생각하면 됩니다. 물품 보관함의 경우 번호가 있지만, 번호가 중요한 것이 아니라, 해당 물품보관함의 키가 중요 합니다. 즉 키만 있으면 키에 해당하는 물품 보관함을 이용할 수 있습니다. Map이 바로 이런 것 입니다.
List계열과 달리 인덱스가 없고, 키와 값만 있습니다. 그리고 당연한 얘기지만, 키는 유니크 해야 합니다. 우리가 값을 관리하고자 한다면 키를 이용해서 값을 관리 할 수 있습니다.
무슨말이냐면 지하철에가면 물품보관함이 있는데 9개칸의 물품보관함이 있다고 한다면 어떠한 물품을 보관한다면 물품을 데이터라 생각하고
1,2,3
4,5,6
7,8,9
가 될텐데 Map계열에서는 번호가 중요한게 아니라 여기를 들어가는 열쇠가 중요한 것이다.
5번을 꺼낸다면 5번의 키가 있어야 할텐데 Map계열에선 인덱스는 존재하지않고 키와 값만 있다.
==========================================================================
package jongkyu.collection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
public class Collections {
public void start() {
ArrayList<String> arrayList = new ArrayList<String>();
//데이터 안에 들어갈 타입이 String타입이다.
//객체니까 생성을 해준 것이다.
//데이터를 넣을때 사용하는게 arrayList.add이다.
arrayList.add("str1");//0번째 인덱스
arrayList.add("str2");//1번째 인덱스
arrayList.add("str3");//2번째 인덱스
arrayList.add("str4");//3번째 인덱스
System.out.println(arrayList.toString()+"a1");//arrayList를 출력해라
String index3 = arrayList.get(3);//문자형 index3 에 arrayList3번째껄 넣어라.
System.out.println("index3 = "+index3+"a2");//str4가 출력된다.
arrayList.set(2, "str2222222");//arrayList 2번째에다가 str22222로바꿔라
System.out.println(arrayList.toString()+"a3");//전체를 출력해라
int size = arrayList.size();//사이즈에다가 배열 사이즈를 넣어라.
System.out.println("size : "+size);//사이즈는 그럼 4이다. 현재 4개가 들어있기 때문이다.
arrayList.remove(2);//배열에 2번째꺼를 지워라.
System.out.println(arrayList.toString()+"a4");//str3이지워진다.
arrayList.clear();//배열을 다 지워라.
System.out.println(arrayList.toString()+"a5");//하나도 표시되지않는다.
arrayList=null;//배열에 null을 넣어라.
System.out.println(arrayList+"a6");//널이 표시된다.
// System.out.println(arrayList.size()+"a7");//객체가 없는 상태에서 사이즈를 출력할려고 하니 에러가 뜬다. 이때 try catch문을 써버리자.
try {
System.out.println(arrayList.size()+"a7");//사이즈가 없는 상태에서 사이즈를 출력할려고 하니 에러가 뜬다. 이때 try catch문을 써버리자.
}catch(NullPointerException e){
System.out.println("값이 없습니다.");
}
}
public void linked() {
LinkedList<String> linkedList = new LinkedList<String>();
//arrayList랑 거의 비슷하다.
//약간의 속도의 차이가 있다. arrayList는 추가할때 속도가더 빠르고
//LinkedList는 꺼내오거나 할때는 속도가 더빠르다 하는데 체감상으론 못느끼기 때문에 둘중 어떤걸 쓰던 상관이 없다.
linkedList.add("str1");
linkedList.add("str2");
linkedList.add("str3");
linkedList.add("str4");
System.out.println(linkedList.toString()+"a11a");
linkedList.add("str5");//뒷부분에 저절로 추가된다.
System.out.println(linkedList.toString()+"a12a");
linkedList.add(2,"STR2");//인덱스 2자리에 STR2가 추가된다.
System.out.println(linkedList.toString()+"a13a");
linkedList.add(2,"STR3");//인덱스2자리에 STR3가 추가된다.
System.out.println(linkedList.toString()+"a14a");
int size = linkedList.size();//사이즈를 보는데 사이즈는 7개가 추가되어있으니 7개로 표시된다.
System.out.println("사이즈는 " + linkedList.size()+"a15a");
linkedList.remove(2);//2인덱스 2번째꺼를 제거한다는 것이다.
System.out.println(linkedList.toString()+"a16a");
linkedList.clear();//깔끔히 지워버렸다.
System.out.println(linkedList.toString()+"a17a");
linkedList=null;//null을 해서
System.out.println(linkedList);
}
public void hashmap() {
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
//hashmap이고 안에데이터는 Integer이 열쇠가 되고 String가 데이터가 되는 것이다. 2개가 매칭되는 것이다. Integer은 유니크해야된다는 것이다.
hashMap.put(0, "str0");//데이터를 추가할때는 put을 쓴다. 0이라는 키에는 str0이라는 데이터가 들어갔다.
hashMap.put(1, "str1");//1이라는 키에는 str1이라는 데이터가 들어갔다.
hashMap.put(2, "str2");
hashMap.put(3, "str3");
//앞에 숫자는 아무거나 써도 상관이 없다.
System.out.println(hashMap.toString());
String str = hashMap.get(2);//어떠한 데이터를 얻어올땐 get을 쓰는데 키값을 써준다. 2에 해당하는 데이터를 얻고싶다.
System.out.println(str);
hashMap.remove(2);//키가 2인녀석의 데이터를 없애달라.
System.out.println(hashMap.toString());
hashMap.clear();//데이터를 다 삭제해라.
System.out.println(hashMap.toString());
hashMap.put(0,"str0");
hashMap.put(1,"str1");
hashMap.put(2,"str2");
hashMap.put(3,"str3");
//똑같이 데이터를 넣었다.
System.out.println(hashMap.toString());
Iterator<Integer> iterator = hashMap.keySet().iterator();
//Iterator안에 데이터는 Integer이 들어간다. hashmap으로부터 데이터를 얻어오는데 keyset은 0,1,2,3이고 이걸 다 얻어왔다. 그후에 iterator을 반복자를 얻어오라는 것이다.
//iterator을 반복자라고 생각하면 된다.
while(iterator.hasNext()) {//반복자에서 다음넥스트가 있느냐 즉 0에서 1이있냐 1에서 2가있냐 이걸 말하는 것이다.
String string=hashMap.get(iterator.next());//0을 갖고왔고 그거에 해당하는 str0을 출력했다.
//그후 다시 돌아와서 다시 1을 갖고왔고 그거에 해당하는 str1을 출력했다.이걸 반복한다.
System.out.println(string);
}
}
}
public class Collections {
private String name;
private int grade;
public Collections() {}//기본생성자
public Collections(String name, int grade) {
this.name=name;
this.grade=grade;
}//생성자 오버로딩
@Override
public String toString() {
return name + " : "+grade;
}
//기본 toString가 해시라는게 데이터를 가리키는 주소값을 정수화 시킨 것인데 hashSet은 다 객체라는게 들어가있는데 toString가 가리키는 메모리의 값들이 찍혔다.
//그걸 바꿀려고 return으로 오버로딩을 한것이다.
}
----------------------------------------------------------------------------------------------
package jongkyu.run;
import java.util.HashSet;
import jongkyu.collection.Collections;
public class Run {
public static void main(String[] args) {
// Collections c = new Collections();
// c.hashset();
//
HashSet<Collections> hashSet = new HashSet<Collections>();
//Hashset을 이용할거고 내가만든 객체 Collections에서 갖고올꺼야
hashSet.add(new Collections("홍길동,",3));//홍길동 3학년을 만들어보겠다.
//new Collections에서 갖고올것이야. 그럼 일단 생성자를 갖고올 것이다.
hashSet.add(new Collections("이순신,",6));
//new Collections에서 갖고올것이야.
hashSet.add(new Collections("장보고,",1));
System.out.println(hashSet.toString());
//toString을 해서 갖고올것인데 만약 보자면 기본 toString같은경우 패키지명@클래스 등등으로 되어있고 뒤에 인스턴스값이 있을텐데 이걸 바꿔준 것이다.
}
}
package jongkyu.run;
import java.util.HashSet;
import jongkyu.collection.Collections;
public class Run {
public static void main(String[] args) {
// Collections c = new Collections();
// c.hashset();
//
HashSet<Collections> hashSet = new HashSet<Collections>();
//Hashset을 이용할거고 내가만든 객체 Collections에서 갖고올꺼야
hashSet.add(new Collections("홍길동",3));//홍길동 3학년을 만들어보겠다.
//new Collections에서 갖고올것이야. 그럼 일단 생성자를 갖고올 것이다.
hashSet.add(new Collections("이순신",6));
//new Collections에서 갖고올것이야.
hashSet.add(new Collections("장보고",1));
System.out.println(hashSet.toString());
//toString을 해서 갖고올것인데 만약 보자면 기본 toString같은경우 패키지명@클래스 등등으로 되어있고 뒤에 인스턴스값이 있을텐데 이걸 바꿔준 것이다.
// Collections collection = new Collections("이순신",6);
// hashSet.remove(collection);
// //이때 그럼 이순신이 지워져야되는데 안지워진다. 왜그러냐면 객체가 다른걸로 인식하기 때문이다.
// System.out.println(hashSet.toString());
//
//이럴경우를 대비해 이렇게 해주면 된다.
Collections collection = new Collections("이순신",6);
hashSet.remove(collection);
System.out.println(hashSet.toString());
}
}
'IT일반과목 > java' 카테고리의 다른 글
MVC패턴으로 소스 짜보기2 (0) | 2018.08.02 |
---|---|
MVC패턴으로 소스 짜보기 (0) | 2018.08.02 |
자바 Collections (0) | 2018.08.01 |
equals, hahscode (0) | 2018.08.01 |
Object 클래스에 대해서 (0) | 2018.08.01 |