Everyday Dev System

0523_TIL : Java 2주차 강의에서 새로 알게된 것 본문

내배캠 주요 학습/TIL : Today I Learned

0523_TIL : Java 2주차 강의에서 새로 알게된 것

chaeyoung- 2023. 5. 23. 15:33

 

# 새롭게 알게된 점 :

 

1. 배열 클래스의 fill이라는 내장 함수를 처음 알았다.

int[] intArr = {10, 20, 30, 40, 50};

for(int i:intArr) {
	System.out.println(i);
}
Arrays.fill(intArr,1);

 

2. 배열의 깊은 복사 메서드로 copeOf 를 활용한다.

// 깊은 복사 메서드

// 1. clone() 메서드
int[] a = {1,2,3,4};
int[] b = a.clone(); // 가장 간단한 방법
// 하지만, clone() 메서드는 2차원이상 배열에서는 얄튼 복사로 동작한다.
        int[] a = {1,2,3,4};
        int[] b = Arrays.copyOf(a, a.length);
        // a라는 배열과 a배열의 길이를 넣어주면 새로운 배열을 반환하여 b라는 배열에담기는 것.

        a[3] = 0;
        System.out.println(a[3]);
        System.out.println(b[3]);
        // 0과 4가 출력이 되는 것을 보면 서로 완전 다른 배열이라는 것을 알수 있다.

 

 

3. 기본형 변수와 참조형 변수의 차이

기본형 변수는 소문자로 시작 / 참조형 변수는 대문자로 시작

  - Wrapper class에서 기본형 변수를 감싸줄 때 (boxing), int -> Integer

기본형 변수는 값 자체를 저장, 참조형 변수는 별도의 공간에 값을 저장 후 그 주소를 저장함(= 주소형 변수)

 

 

4. String 클래스의 유용한 내장 함수로는

- charAt() 

- substring(0,3)

- .equals(str)

 

 

5. 가변배열

int[][] array = new int[3][];

array[0] = new int[2];
array[1] = new int[4];
array[2] = new int[1];

//중괄호로 초기화를 아예 해버릴 때도 가능함!
int[][] array2 = {
				{10, 20}
				{10, 20, 30, 40}
				{10}
                };

 

 

6. Collection

- 배열보다 다수의 참조형 데이터를 더 쉽고 효과적으로 처리할 수 있는 기능을 많이 갖고 있음.

기능 : 크기 자동 조정/ 추가 / 수정/ 삭제 / 반복 / 순회 / 필터 / 포함확인 등.

List , Set , Queue , Map

set은 집합이라고 생각하면 된다. 중복 미허

Map은 key , value로 이루어진 것이므로 중복 미허용

 

List는 순서가 있는 데이터의 집합으로, 처음에 길이를 몰라도 만들 수 있음.

Array는 정적배열, List(ArrayList) -> 동적배열(크기가 가변적으로 늘어난다.)

- add, set, remove, clear

        ArrayList<Integer> intList = new ArrayList<Integer>();
        intList.add(99);
        intList.add(15);
        intList.add(3);

        System.out.println(intList.get(1));

        // 2번째 있는 값(15->10) 변경
        intList.set(1,10);
        System.out.println(intList.get(1));

        //삭제
        intList.remove(0);
        System.out.println(intList.get(0));

        intList.clear();
        System.out.println(intList.toString());

 

LikedList

 

메모리에 남는 공간을 요청해서 여기 저기 나누어서 실제 값을 담음.
실제 값이 있는 주소값으로 목록을 구성하고 저장하는 자료구조

기본적 기능은 -> ArrayList와 동일하다
조회하는 속도가 느리다.
값 추가,삭제 빠름

 

Stack<Integer> intStack = new Stack<Integer>();

stack - add,  peek,  pop, isEmpty(),  size()

 

Queue<Integer> intQueue = new LinkedList<>();

Queue- add, peek, poll, isEmpty(), size()

 

Set<Integer> intSet = new HashSet<>();

set은 순서가 보장되지 않는 대신 중복을 허용하지 않는 자료구조

- HashSet, TreeSet

- add, contains(), 

 

        Map<String, Integer> intMap = new HashMap<>();

        intMap.put("일",1);
        intMap.put("일",1);
        intMap.put("일",1);

        for(String key : intMap.keySet()){
            System.out.println(key);
        }

        for(Integer values : intMap.values()){
            System.out.println(values);
        }

Map 

key - value 

- put, keySet(), values(), get