본문 바로가기
CLASS/JAVA

#13-3 / Map클래스배열(Key배열)

by eungSe__ 2024. 5. 20.

ArrayList,LinkedList는 key배열 아님

Map<K, V> => key : 데이터값, value

Map-가장 큰단위 , 그 안에 자식 Hashmap,Hashtable,TreeMap (List와 같다고 생각하면 됨)

Interface임 ( ArrayList,LinkedList  얘네는 class) - List처럼 엄마만 Interface,하위는 class

 

👀

{product=모니터} 이런 형식으로 출력됨

int사용 불가 - Integer사용 (List와 동일)

중복된 key 사용 불가 

Hashmap -> ArrayList -> LinkdedList 로 변환해서 프론트에게 전달! (실무에선 이렇게 사용함)

 

👀

Hashtable : 데이터 병렬처리 및 Thread

HashMap : 단일 처리 및 Single Thread (웹에서 빠름)

 

  ❗ 배열은 2가지로 나뉨 : 데이터배열 / key가 존재하는 배열(실무 사용 많음)  

⚡ Map1
public class map1 {

	public static void main(String[] args) {
		Map<String, String> map1 = new HashMap<String, String>();

		//이렇게 작성해도됨 List,ArrayList처럼
		//HashMap<String, String> map2 = new HashMap<String, String>();
		
		map1.put("product", "모니터");
		map1.put("product2", "키보드");
		//{product=모니터, product2=키보드} 출력 , 중복된 key 사용 불가
		System.out.println(map1); 
		
		//등록된 key를 이용하여 데이터를 출력
		System.out.println(map1.get("product")); //모니터 출력
		
		//등록된 키 현황 출력 - [product, product2] 출력
		System.out.println(map1.keySet()); 

	}

}

 

⚡ key배열 만들기(HashMap + ArrayList)
프론트에게 전달시 이렇게 사용
public static void main(String[] args) {
    ArrayList<String> one = new ArrayList<String>(); //1차배열
    one.add("홍길동");
    one.add("강감찬");
    one.add("이순신");
    one.add("유관순");

    HashMap<String, ArrayList<String>> data = new HashMap<String, ArrayList<String>>();

    data.put("member", one); //대표키 생성 및 1차 클래스배열 입력

    //{member=[홍길동, 강감찬, 이순신, 유관순]} 출력
    System.out.println(data);

    //foreach를 이용하여 대표키를 설정한 후,해당 대표키에 적용된 데이터 출력
    for(String mb : data.get("member")) {
        System.out.println(mb); //각 data 한줄씩 출력
    }

    System.out.println(data.size()); //1 출력(key 갯수 확인)
    System.out.println(data.get("member").size()); //4 출력(key값에 따른 데이터 갯수 확인)

    data.remove("member"); //대표키 삭제시 해당 그룹 내 데이터 모두 삭제
    System.out.println(data); //{} 싹 사라짐


}

 

⚡ HashTable 사용
HashMap과의 차이 
- all.put(4, null); null값 Hashtable에선 사용 불가하나 HashMap에선 가능
public static void main(String[] args) {
    Hashtable<Integer, String> all = new Hashtable<Integer, String>();
    all.put(0, "HTML");
    all.put(1, "CSS");
    all.put(2, "JS");
    //all.put(4, null); null값은 Hashtable에선 사용 불가하나 HashMap에선 가능
    System.out.println(all); //{2=JS, 1=CSS, 0=HTML}
    System.out.println(all.get(0)); //HTML
    System.out.println(all.keySet()); //[2, 1, 0] - key종류 다 가지고 옴

    int w=0;
    while(w<all.keySet().size()) { //key갯수만큼 돌림
        System.out.println(all.get(w)); //각 데이터 출력

        w++;
    }

}

 

- oop 끝 -

'CLASS > JAVA' 카테고리의 다른 글

#14-1 / FileReader => Buffer  (0) 2024.05.21
#13-4 / I/O 🔥  (0) 2024.05.20
#13-2 / Thread  (0) 2024.05.20
#13-1 / String, StringBuilder, StringBuffer  (0) 2024.05.20
#12 / remind2  (0) 2024.05.17