Java Collections Framework

별의개발자커비·2023년 2월 17일
0

Java

목록 보기
50/71
post-thumbnail

ArrayList와 컬렉션즈 프레임워크

  • 가장 많이 사용하는 Collections Framework 기능 중에 하나
class Main {

    public static void main(String[] args) {
        ArrayList<String> al = new ArrayList<String>(); //3. 제네릭 방식: al에 추가되는 값은 String으로 지정해주는 것
        al.add("one"); // 1. add()는 ArryayList에 저장될 때 Object 데이터타입으로 저장됨
        al.add("two");
        al.add("three");
        for(int i=0; i<al.size(); i++){
					String value = (String)a1.get(i); 
					// 2. 현재 get(i)의 데이터타입은 Object라 안맞음 => (String) 형변환 필요
					// 근데 이건 옛날 방식 -> 제네릭을 쓰자!
            System.out.println(al.get(i));
        }
    }
}

Linkedlist

arrayList가 중간에 새로운 걸 삽입할 때 원래 배열 안에 것들이 한 칸씩 밀리게 된다면,
LinkesList는 중간에 새로운 걸 링크만 시켜주는 것

컬렉션즈 프레임워크란?

List와 Set의 차이점

  • List는 중복을 허용하고 저장되는 순서가 유지되지만
  • Set는 중복을 허용하지 않고 순서가 없다.

Set

//Please don't change class name 'Main'
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

class Main {

    public static void main(String[] args) {
        HashSet<Integer> A = new HashSet<Integer>();
        A.add(1);
        A.add(2);
        A.add(3);

        HashSet<Integer> B = new HashSet<Integer>();
        B.add(3);
        B.add(4);
        B.add(5);

        HashSet<Integer> C = new HashSet<Integer>();
        C.add(1);
        C.add(2);

        System.out.println(A.containsAll(B)); // : B는 A의 부분집합인가? = false 
        System.out.println(A.containsAll(C)); // true

        //A + B 
        A.addAll(B); // : A는 A와 B의 합집합으로 하겠다. = 1 2 3 4 5

        //A와 B의 교집합
        A.retainAll(B); // : A는 A와 B의 교집합만 갖겠다. = 3

        //A - B
        A.removeAll(B); // : A는 A에서 B를 뺀 차집합만 갖겠다. = 1 2

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

iterator

  • 메소드 iterator는 인터페이스 Collection에 정의되어 있다. 따라서 Collection을 구현하고 있는 모든 컬렉션즈 프레임웍크는 이 메소드를 구현하고 있음을 보증한다. 메소드 iterator의 호출 결과는 인터페이스 iterator를 구현한 객체를 리턴한다.
    이러한 기능을 조합하면 for 문을 이용하는 것과 동일하게 데이터를 순차적으로 처리할 수 있다.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

class Main {

    public static void main(String[] args) {
        HashSet<Integer> A = new HashSet<Integer>();
		// ArrayList<Integer> A = new ArrayList<Integer>();
		// ArrayList의 경우에도 아래 코드 사용 가능
		// -> 컬렉션 인터페이스를 구현하는 모든 클래스들은 iterator 사용할 수 있도록 강제되어있어서

        A.add(1);
        A.add(2);
        A.add(3);
			
        Iterator hi = A.iterator(); 
        // iterator() 메소드: A인스턴스에 들어있는 값과 똑같은 값을 가지는 
        // 가상의 컨테이너 hi를 만들어주는 것
        while(hi.hasNext()){ // hasNext(): hi안에 들어있는 값들이 존재하는지 true,false 리턴
            System.out.println(hi.next()); 
			// next(): hi에 들어있는 값중에 하나를 호출하고 그 값을 집합에서 없앰
			// 단, hi라는 A의 참조값을 가지는 컨테이너 안에 있는 값이 없어지는 거라 
            // 원본 A에는 영향이 없음
        }
    }
}

map

Map 컬렉션

  • key와 value의 쌍으로 값을 저장하는 컬렉션
import java.util.*;

class Main {

    public static void main(String[] args) {
        HashMap<String, Integer> a = new HashMap<String, Integer>();
				// HashMap<key의 데이터타입, value의 데이터타입>
        a.put("one", 1); // put(one, 1): map의 메소드로
        a.put("two", 2); // = a라고 하는 map 카테고리에 해당되는 컨테이너에 데이터를 추가하는데
        a.put("three", 3); // key값 = one , value값 = 1이다.
        System.out.println(a.get("one")); // get("one"): one이라고하는 key의 value값 리턴한다.

학원

//4

package day4_generic;

import java.util.HashMap;
import java.util.Map;

public class MapDemo {

	public static void main(String[] args) {
		// key value 한 쌍...  key 에 들어가는 값은 unique 하다
		Map <String, Integer > map = new HashMap <String, Integer >();
		map.put("123", 123);
		map.put("123", 45);
		map.put("123", 156); // key 값이 같으므로 update
		
		System.out.println(map.get("123"));
		System.out.println(map.size());

		map.put("456", 45);
		System.out.println(map.size());
		
		map.remove("123");
		System.out.println(map.size());
		
		map.remove("1235");
		System.out.println(map.size());

	}

}

//4

package day4_generic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapDemo2 {

	public static void main(String[] args) {

		List <Map<String, String>> lists = new ArrayList <Map<String, String>> ();
		Map<String, String> maps = new HashMap<String, String>();
		lists.add(maps);	// 여기?
		maps.put("name", "a");
		maps.put("age", "29");
		maps.put("id", "b");
//		lists.add(maps);	// 여기?
		
		maps = new HashMap<String, String>(); // 이름은 같지만 새로운 주소값이 생긴 것
		maps.put("name", "f");
		maps.put("age", "39");
		maps.put("id", "g");
		lists.add(maps);
		
		System.out.println(lists);
	}

}
  • 활용
class Main {

    public static void main(String[] args) {
        HashMap<String, Integer> a = new HashMap<String, Integer>();
        a.put("one", 1);

        iteratorUsingForEach(a);
        iteratorUsingIterator(a);
    }

	// 방법 1
    static void iteratorUsingForEach(HashMap map){
        Set<Map.Entry<String, Integer>> entries = map.entrySet(); 
		// map.entrySet(): Set 데이터타입에 어떤 객체가 리턴되는데 그 객체가 entries 변수에 담기게 됨
		// map과 똑같은 값들을 담고 있는 Set 데이터타입 컨테이너가 생기게 되는 건데
		// Set에 담겨있는 값들은 Map 인터페이스가 갖고있는 Entry 인터페이스를 구현하고 있는 어떠한 객체들이다.
		// Map.Entry 데이터타입에는 getKey getValue 
		// <String, Integer>에서 String = getKey의 데이터타입, Integer = getValue의 데이터타입
        for (Map.Entry<String, Integer> entry : entries) { // Set 데이터타입의 entries들을 반복문
            System.out.println(entry.getKey() + " : " + entry.getValue());
        } // map에는 iterator 기능이 없으므로? 
		// -> Map에 담겨있는 데이터들을 Set에 옮겨담고 그 Set에 들어가있는 데이터들의 데이터타입은 Map.entry인데 
		// 각각의 키값은 getKey로 value값은 getValue값으로 알아낸다.
    } 

	// 방법 2
    static void iteratorUsingIterator(HashMap map){
        Set<Map.Entry<String, Integer>> entries = map.entrySet(); //entrySet()을 이용해 map데이터들에 대응되는 걸 Set entries에 담았고 
        Iterator<Map.Entry<String, Integer>> i = entries.iterator(); // 그 entries는 Set이기 때문에 iterator로 거기있는 값을 반복자로 사용할 수 있음 = 그걸 i에 담았음
        while(i.hasNext()){ // 그 i를 조회할 데이터가 있는지 확인하고
            Map.Entry<String, Integer> entry = i.next(); // iterator안에 들어있는 데이터를 하나하나 꺼내는데 (그 꺼내진 값들은 Map.Entry라는 데이터타입을 가지고 있음)
            System.out.println(entry.getKey()+" : "+entry.getValue()); // 걔의 key, value 출력함
        }
    }
}

정렬 Collections

  • 컬렉션을 사용하는 이유 중의 하나는 정렬과 같은 데이터와 관련된 작업을 하기 위해서다. 정렬하는 법을 알아보자. 패키지 java.util 내에는 Collections라는 클래스가 있다. 이 클래스를 사용하는 법을 알아보자.
import java.util.*;

class Computer implements Comparable{ // 3. sort를 쓰려면 Comparable 인터페이스 implements되어야
    int serial;
    String owner;
    Computer(int serial, String owner){
        this.serial = serial;
        this.owner = owner;
    }
    public int compareTo(Object o) { // 4. Comparable는 a.compareTo(b)메소드를 구현하도록 강제되어있음
			// 5. a = b 면 0, a<b 음수, a>b면 양수여야 함
        return this.serial - ((Computer)o).serial;
			// = return a.serial - b.serial : a가 크면 양수, b가 크면...
    }
    public String toString(){
        return serial+" "+owner;
    }
}

class Main {

    public static void main(String[] args) {
        List<Computer> computers = new ArrayList<Computer>(); // 
        computers.add(new Computer(500, "egoing"));
        computers.add(new Computer(200, "leezche"));
        computers.add(new Computer(3233, "graphittie"));
        Iterator i = computers.iterator();
        System.out.println("before");
        while(i.hasNext()){
            System.out.println(i.next());
        }
				
        System.out.println("\nafter"); // 6. 출력 결과
			// 1. Collections라는 클래스: 정렬 등 데이터관련 작업 처리 도와주는 클래스, 활용할 수 있는 메소드도 다양
			//다 static 메소드라 클래스 인스턴스화안하고 바로 부를 수 있음
        Collections.sort(computers); // 2. sort 메소드의 인자로 List데이터타입을 전달하면 얘를 sort가 정렬해줌
        i = computers.iterator();
        while(i.hasNext()){
            System.out.println(i.next());
        }
    }
}
  • 실행결과

    	before
    	500 egoing
    	200 leezche
    	3233 graphittie
    
    	after
    	200 leezche
    	500 egoing
    	3233 graphittie

( 출처 생활코딩 https://www.opentutorials.org/course/1194/6446 )

profile
비전공자 독학러. 일단 쌔린다. 개발 공부👊

0개의 댓글