본문 바로가기

KOSTA : 클라우드 네이티브 애플리케이션 개발 전문가 양성과정

05/09 21일차 컬렉션

728x90

 

 
 
 
 

배열

int - 단일 타입

int[] - 같은 여러 개 데이터 타입

 

- 메모리 연속적으로 할당합니다

- 반드시 메모리에 생성 후 사용합니다

int[] arr = new int[5]; // 정확한 갯수 지정

- 다른 타입 데이터를 저장하고, 쉽게 데이터를 넣고 뺄 수 있게 컬렉션 프레임워크를 이용합니다.

 

컬렉션

- 정해진 크기 없이 여러개의 데이터를 저장합니다.

- 다른 타입들을 다양하게 여러 개를 저장할 수 있습니다

- 보통 정보를 담기 위한 용도이고, 담은 정보들을 없애는 일은 잘 하지 않습니다.

- List는 입력에 좋습니다.

- Set은 distinct 기능을 수행할 때 좋습니다.

- Map은 출력에 좋습니다. 값을 key이름으로 매핑했기 때문에, key값을 확인하여 무슨 데이터인지 확인하기 쉽습니다.

int res = arr[0][1] + arr[0][10];
logWrite(res);

 

많이 쓰는 컬렉션

- ArrayList 

- HashSet

- Vector

 

Java api 보는 방법

 

Constructor Summary

ConstructorsConstructor and Description

HashSet()
Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
HashSet(Collection<? extends E> c)
Constructs a new set containing the elements in the specified collection.
HashSet(int initialCapacity)
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).
HashSet(int initialCapacity, float loadFactor)
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.
HashSet hs = new HashSet();
HashSet hs = new HashSet(16);
HashSet hs = new HashSet(16,0.75);
HashSet hs = new HashSet(Collection);

 

캐스팅

- 작은 <--- 큰 : down casting (강제 형변환)

- 큰 <----- 작은 : up casting (형변환 생략 가능)

 

제네릭(Generic)

 

 컴파일 시 클래스, 메서드 등에서 사용할 데이터 타입을 미리 지정하는 방법입니다.

- 컴파일 시 컴파일러가 사전에(구동전에) 타입을 체크합니다.

- 사용시 장점으로 타입 안정성, 코드가독성, 런타임 시 오버헤드 감소가 있습니다.

 

Set

-입력

HashSet hs = new HashSet();
hs.add("abc");
hs.add(10);
hs.add('A');
hs.add('A');
hs.add('A');
System.out.println(hs); //[abc,10,A]

-수정

//수정불가, 기존의 값을 지우고 신규 값으로 입력

HashSet hs = new HashSet();
hs.add("abc");
hs.add(10);
hs.add('A');

hs.remove("abc");
hs.add("zzz");
System.out.println(hs) // [zzz,10,A]

-형변환

// 형변환 : Set --> ArrayList
HashSet hs = new HashSet();
hs.add("abc");
hs.add(10);
hs.add('A');

ArrayList list = new ArrayList(hs);
System.out.print(list.getClass());

 

List

-입력

ArrayList list = new ArrayList();

list.add("abc");
list.add("10");
list.add('A');

System.out.println(list.get(1).getClass())

-출력

ArrayList list = new ArrayList();

list.add("abc");
list.add(10);
list.add('A');

System.out.println(list);

for(int i=0;i<list.size();i++){
	System.out.print(list.get(i)+" ");
}

-수정

ArrayList list = new ArrayList();

list.add("abc");
list.add(10);
list.add('A');

list.add(3,"def"); // 3번째 def 추가
list.set(0,"zzz"); // 0번째 zzz로 수정

System.out.print(list); // [zzz,10,A,def]

-삭제

ArrayList list = new ArrayList();

list.add("abc");
list.add(10);
list.add("A");

list.remove(1); // 인덱스 1번째 삭제
list.remove("10"); // "10"은 없어서 삭제안됨, 정수값 10으로 삭제
list.remove(Integer.valueOf(10));

-추가기능

int idx = list.indexOf("def");
System.out.println(idx);

Map

-입력

HashMap map = new HashMap();

map.put("name","abc");
map.put("age",10);
map.put("score",'A');
map.put("score",'B');

System.out.println(map); // {score:A, name=abc, age=10}

-출력

HashMap map = new HashMap();

map.put("name","abc");
map.put("age",10);
map.put("grade",'A');

System.out.println(map);
System.out.println(map.get("name").getClass());

// 작은 <-- 큰 : down casting(강제 형변환)
// 큰 <-- 작은 : up casting(형변환 생략가능)
// 레퍼클래스 (wrapper class)
// int --> Integer

String str = (String)map.get("name");
int num = (Integer)map.get("age");
System.out.println(str+","+num);

-수정

//put(기존키값, 변경값)
//replace(기존키, 변경값)

HashMap map = new HashMap();
map.put("name","zzz");
map.put("age",10);
map.put("grade",'A');

map.put("name","zzz");
System.out.println("변경후:"+map);

// 제네렉(Generic)
// (컴파일 시) 클래스, 메서드 등에서 사용할 데이터 (타입을 미리 지정)하는 방법
// 컴파일 시 컴파일러가 사전에 타입 체크
// 타입안정성, 코드가독성, 런타임 시 오버헤드 감소

HashMap<String,String> map2 = new HashMap<String,String>();
map2.put("name" , "abc");
map2.put("addr" , "서울");

// 제네릭을 사용함으로써 형변환 생략 가능(매우중요)
String str2 = map2.get("name");

-삭제

 

타입출력

 

컬렉션을 이용한 입력과 출력

//ArrayList(ArrayList)
		ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
		
		for(int i=0;i<4;i++) {
			ArrayList<String> arr = new ArrayList<String>();
			arr.add(""+i+1);
			arr.add("제목"+(i+1));
			arr.add("2024-01-01");
			arr.add("kim"+i);
			list.add(arr);
		}
		
		for(int i=0;i<list.size();i++) {
			String seq = list.get(i).get(0);
			String title = list.get(i).get(1);
			String rdate = list.get(i).get(2);
			String regid = list.get(i).get(3);
			
			System.out.println(seq+"\t"+title+"\t"+rdate+"\t"+regid);
		}

 

	//ArrayList(HashMap)
		
		ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
		HashMap<String,String> hm = new HashMap<String,String>();
		hm.put("seq", "1");
		hm.put("title", "제목1");
		hm.put("rdate", "2024-01-01");
		hm.put("name", "kim");
		list.add(hm);
		
		HashMap<String,String> hm2 = new HashMap<String, String>();
		hm2.put("seq", "1");
		hm2.put("title", "제목2");
		hm2.put("rdate", "2024-02-02");
		hm2.put("name", "kim");
		list.add(hm2);
		
		for(int i=0;i<list.size();i++) {
			String seq = list.get(i).get("seq");
			String title = list.get(i).get("title");
			String rdate = list.get(i).get("rdate");
			String name = list.get(i).get("name");
			System.out.print(seq+"\t"+title+"\t"+rdate+"\t"+name);
			System.out.println();
		}