본문 바로가기

IT일반과목/java

자바 Collections 2

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);

}

}


}


===============================================================================================
HashSet
Set게열의 자료구조에서는 데이터의 순서는 없다. 하지만 중복된 데이터는 허락하지 않는다.
hashSet을 가기전에 Hash같은 경우는 으깨다 이런 뜻인데 set계열의 자료구조에서는 데이터의 순서는 상관이 없다. 중복된 데이터만 허락하지 않는다.
클래스가 있다면 그거에 대한 객체를 2개를 생성했다. 동일한 클래스에서 나왔지만 객체를 생성한 순간 가리키는 레퍼런스는 다르다.
래퍼런스에 담긴 주소값이 어디 객체를 가르키냐에 따라 주소값이 다를 것이다.
이럴때 이 객체들이 갖고있는 주소값을 정수화 시켜놓은 값을 해시값이라 한다.

package jongkyu.collection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
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 void hashset() {
HashSet<String> hashSet = new HashSet<String>();
//hashSet을 가기전에 Hash같은 경우는 으깨다 이런 뜻인데 set계열의 자료구조에서는 데이터의 순서는 상관이 없다. 중복된 데이터만 허락하지 않는다.
//클래스가 있다면 그거에 대한 객체를 2개를 생성했다. 동일한 클래스에서 나왔지만 객체를 생성한 순간 가리키는 레퍼런스는 다르다.
//래퍼런스에 담긴 주소값이 어디 객체를 가르키냐에 따라 주소값이 다를 것이다.
//이럴때 이 객체들이 갖고있는 주소값을 정수화 시켜놓은 값을 해시값이라 한다.
//HashSet에 String문자열 값을 넣어줄 것이다.
hashSet.add("str0");//데이터 추가할때 add를 써주는데 String문자열 하나씩 들어간다.
hashSet.add("str1");
hashSet.add("str2");
hashSet.add("str3");
hashSet.add("str2");
System.out.println(hashSet.toString());//데이터를 출력한다.
hashSet.remove("str0");//str0에 해당하는 값이 삭제해라.
System.out.println(hashSet.toString());
int i=hashSet.size();//갖고있는 사이즈를 구해라
System.out.println("사이즈 : "+i);
}
}

==================================================================================




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());

}

}


------------------------------------------------------------------------------------------------------------------------------------
package jongkyu.collection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;

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으로 오버로딩을 해서 
@Override//객체에서 지울려고 이걸 쓴것이다.
public boolean equals(Object obj) {
String compareValue = obj.toString();
//오브젝트의 toString은 바로위에 있는 toString을 말한것이다.
String thisValue = toString();
//이거는 같
return thisValue.equals(compareValue);
}//equals를 갖고오고
@Override//객체에서 지울려고 이걸 쓴것이다.
public int hashCode() {
return toString().hashCode();
}//hashCode를 오버라이드 한다.
//해당객체에 hashCode를 뽑아준다.


'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