아무거나

JAVA Collections 본문

Java/Java

JAVA Collections

전봉근 2019. 8. 16. 23:38
반응형

[JAVA Collections]

컬렉션이란, 우리말로 쉽게 말해서 자료구조 입니다. 더 쉽게 말하면 배열입니다.

어려운 자료구조형의 내부를 공부할 필요 없이 그냥 편하게 사용하면 된다.

JAVA에서는 다양한 자료구조형을 제공하고 있다. 다양한 자료구조형이 제공되는 이유는 데이터의 성질에 따라서

데이터를 관리(정리)해야 하는 방식이 다르기 때문입니다.

여기서 한가지 중요한 것은 자료구조형안에서는 객체의 레퍼런스만을 관리한다.

 

1. List계열 컬렉션 클래스

-> 자료구조중 아마도 가장 많이 사용되고 쉽게 사용할 수 있는 자료구조형이 List계열이 아닐까 합니다.

List는 배열과 비슷하지만, 배열의 단점을 보완 하였습니다. List는 처음 만들 때 크기를 고정하지 않아도 됩니다.

* arrayList랑 linkedList랑 속도차이는 크게 없으나 arrayList가 데이터를 추가하거나 그럴때 속도가 조금 더 빠르며

linkedList는 추가한 데이터를 꺼내올떄(검색) 조금 더 빠르다고한다. 하지만 이 속도차이는 매우 적어서

거의 못느낀다고한다.

 

# ArrayList : 배열과 매우 비슷. 인덱스가 존재하며, 데이터는 중복되어도 상관 없다. (인덱스가 가장 중요)

ex) ArrayList arrayList = new ArrayList(); // String 타입의 데이터를 넣는다고 선언

arrayList.add("str1"); // 데이터추가

arrayList.add("str2");

arrayList.add("str3");

arrayList.add("str4");

System.out.println(arrayList.toString()); // 결과 : [str1, str2, str3, str4]

 

String index3 = arrayList.get(3);

System.out.println("index3 = " + index3); // 결과 : index3 = str4

 

arrayList.set(2, "str2222222");

System.out.println(arrayList.toString()); // 결과 : [str1, str2, str2222222, str4]

 

int size = arrayList.size();

System.out.println("size : " + size); // 결과 : size : 4

 

arrayList.remove(2);

System.out.println(arrayList.toString()); // 결과 : [str1, str2, str4]

 

arrayList.clear(); // 주소값을 초기화 시켜준다. gc가 회수에서 메모리 재활용을 한다. (객체는 그대로 살아있음, 아래의 arrayList=null은 객체를 끊어버리는것이다.)

System.out.println(arrayList.toString()); // 결과 : []

 

arrayList = null;

System.out.println(arrayList); // 결과 : []

System.out.println(arrayList.size()); // 결과 : null -> 이건 버그로 출력된다. 왜냐하면 가리키는 객체가 없는데(객체를 끊었는데) 가리키라하니 에러가난다.

 

# LinkedList : ArrayList와 거의 비슷하다.

ex) LinkedList linkedList = new LinkedList();

 

linkedList.add("str1");

linkedList.add("str2");

linkedList.add("str3");

linkedList.add("str4");

System.out.println(linkedList.toString()); // 결과 : [str1, str2, str3, str4]

 

linkedList.add("str5");

System.out.println(linkedList.toString()); // 결과 : [str1, str2, str3, str4, str5]

 

linkedList.add(2, "STR2");

System.out.println(linkedList.toString()); // 결과 : [str1, str2, STR2, str3, str4, str5]

 

linkedList.set(2, "STR3");

System.out.println(linkedList.toString()); // 결과 : [str1, str2, STR3, str3, str4, str5]

 

int size = linkedList.size();

System.out.println("사이즈는 " + linkedList.size()); // 결과 : 사이즈는 6

 

linkedList.remove(2);

System.out.println(linkedList.toString()); // 결과 : [str1, str2, str3, str4, str5]

 

linkedList.clear();

System.out.println(linkedList.toString()); // 결과 : []

 

linkedList = null;

System.out.println(linkedList); // 결과 : null

 

# Vector : ArrayList와 비슷하지만 속도가 떨어진다. 하지만 ArrayList보다 멀티스레드 환경에서는 안전하여, 여전히 많이 쓰이고 있다.

 

 

2. Map계열 컬렉션 클래스

-> Map계열의 자료구조는 쉽게 생각해서 지하철에 비치되어 있는 물품 보관함을 생각하면 된다. 물품 보관함의 경우 번호가 있지만

번호가 중요한 것이 아니라, 해당 물품보관함의 키가 중요 합니다. 즉 키만 있으면 키에 해당하는 물품 보관함을 이용할 수 있다.

Map이 바로 이런것이다. List계열과 달리 인덱스가 없고, 키와 값만 있습니다. 그리고 당연한 얘기지만, 키는 유니크해야 한다.

우리가 값을 관리하고자 한다면키를 이용해서 값을 관리 할 수 있다.

 

# HashMap

ex) HashMap hashMap = new HashMap(); // Integer은 키값, String은 밸류값

 

hashMap.put(0, "str0"); // 0이라는 키에는 str0이라는 데이터가 들어간다.

hashMap.put(1, "str1"); // 키는 유니크한거이므로 1이 10이되도 상관없다.

hashMap.put(2, "str2");

hashMap.put(3, "str3");

System.out.println(hashMap.toString()); // 결과 : {0=str0, 1=str1, 2=str2, 3=str3}

 

String str = hashMap.get(2);

System.out.println(str); // 결과 : str2

 

hashMap.remove(2);

System.out.println(hashMap.toString()); // 결과 : {0=str0, 1=str1, 3=str3}

 

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()); // 결과 : {0=str0, 1=str1, 2=str2, 3=str3}

 

Iterator iterator = hashMap.keySet().iterator(); // keySet : 위의 0,1,2,3의 순차적으로 갈수있는 반복자를 얻어오라는것이다.

while (iterator.hasNext()) { // hashNext : 다음께 있는지 확인

String string = hashMap.get(iterator.next()); // keySet의 next(); 는 str0을 의미한다. 즉, 0의 해당되는 hashMap의 데이터를 가져옴

System.out.println(string);

}

 

* Iterator : 반복자

 

 

3. Set계열 컬렉션 클래스

-> Set계열 자료구조에서는 데이터의 순서는 없습니다. 하지만 중복된 데이터는 허락하지 않는다.

 

# HashSet

ex) HashSet hashSet = new HashSet();

hashSet.add("str0");

hashSet.add("str1");

hashSet.add("str2");

hashSet.add("str3");

hashSet.add("str2");

System.out.println(hashSet.toString()); // 결과 : [str3, str1, str2, str0]

 

hashSet.remove("str0");

System.out.println(hashSet.toString()); // 결과 : [str3, str1, str2]

 

int i = hashSet.size();

System.out.println("사이즈 : " + i); // 사이즈 : 3

 

ex2) [MainClass.java]

import java.util.HashSet;

 

public class MainClass {

public static void main(String[] args) {

HashSet hashSet = new HashSet();

hashSet.add(new Student("홍길동", 3));

hashSet.add(new Student("이순신", 6));

hashSet.add(new Student("장보고", 1));

 

// 바로 출력해보면 메모리의 주소값이 찍힌다.

// [com.javalec.col.Student@677327b6, com.javalec.col.Student@1540e19d, com.javalec.col.Student@14ae5a5]

System.out.println(hashSet.toString());

 

// Student 클래스에서 오버라이딩하면 값이 제대로표시된다.

// hashSet은 hash값을 가지고 고유한 데이터가 들어가는 방식이므로 데이터가 들어가는 순서가 없다.

 

Student student = new Student("이순신", 6);

hashSet.remove(student);

// 출력해보면 이순신이 지워지지 않았다.

// 이유는 위의 기초데이터로 hashSet.add한 메모리의 주소값과 아래 사용자 객체로 student.remove한 메모리의 주소값이 다르기 때문

// -> 쉽게 말해 먼저만든거하고 나중에 만든거하고는 주소값이 다르기 때문이다.

System.out.println(hashSet.toString());

 

// 위의 주소값이 다른 부분 때문에 Student객체에 equals와 hashCode를 오버라이딩 하면 데이터 삭제가 가능하다.

}

}

 

[Student.java]

public class Student {
    private String name;
    private int grade;

    public Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }


    @Override
    public String toString() {
    	return name + " : " + grade;
    }

    @Override
    public boolean equals(Object obj) {
        String compareValue = obj.toString(); // name+":"+grade 값을 의미
        String thisValue = toString(); // 현재 내가 갖고있는 객체의 toString 값
        return thisValue.equals(compareValue); // 위 두개 값이 같으면 true
    }


    @Override
    public int hashCode() {
        // toString()의 해시값을 얻어와서 바로 리턴한다.
        return toString().hashCode();
    }
}

 

 

4. Iterator 자료구조

-> 자바에서는 Iterator라는 인터페이스가 있다. 이것은 "반복자" 라는 의미로 데이터를 반복적으로 검색하는데

아주 유용한 인터페이스 이다. (참고로 모든 자료구조형은 iterator() 메소드를 지원 하고 있다.)

 

[ex]

 

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;


public class MainClass {
    public static void main(String[] args) {

    ArrayList arrayList = new ArrayList();
    arrayList.add("str0");
    arrayList.add("str1");
    arrayList.add("str2");

    Iterator iterator = arrayList.iterator();
    while (iterator.hasNext()) {
    	System.out.println(iterator.next());
    }
}

 

[결과]

str0

str1

str2

 

 

HashMap hashMap = new HashMap();
hashMap.put(0, "atr0");
hashMap.put(1, "atr1");
hashMap.put(2, "atr2");
hashMap.put(3, "atr3");
hashMap.put(4, "atr4");
System.out.println(hashMap.toString());

Set set = hashMap.keySet();
Iterator iterator = set.iterator();


while (iterator.hasNext()) {
    Integer key = iterator.next();
    System.out.println(key + " : " + hashMap.get(key));
}

 

[결과]

{0=atr0, 1=atr1, 2=atr2, 3=atr3, 4=atr4}

0 : atr0

1 : atr1

2 : atr2

3 : atr3

4 : atr4

반응형

'Java > Java' 카테고리의 다른 글

스레드(Thread)  (0) 2019.08.16
입출력(I/O)  (0) 2019.08.16
예외처리  (0) 2019.08.16
StringTokenizer 클래스  (0) 2019.08.16
Timer 클래스  (0) 2019.08.16
Comments