반응형

프론트엔드 개발자는 가끔 자바스크립트로 문제를 풀어야한다. 하지만, 애처롭게도 c++에는 내장 라이브러리로 존재하는 binary_search, lower_bound, upper_bound가 존재하지 않느다. 따라서, 우리는 이분탐색을 "직접" 만들어야한다. 이분탐색에 대해 알아보자

 

Binary Search

const binarySearch =(arr, target)=>{
    let left = 0;
    let right = arr.length - 1;

    while(left <= right){
        let mid = Math.floor((left+right)/2);

        if(arr[mid] === target){
            return mid;
        }else if(arr[mid] < target){
            left = mid + 1;
        }else{
            right = mid - 1;
        }
    }

    return -1;
}

 

Lower Bound

const lowerBound =(arr, target)=>{
    let left = 0;
    let right = arr.length - 1;

    while(left < right){
        let mid = Math.floor((left+right)/2);

        if(arr[mid] < target){
            left = mid + 1;
        }else{
            right = mid;
        }
    }
    return left;
}
  • lower bound 는 배열에서 타겟값 이상이 처음으로 나타나는 위치를 찾는다.
  • 이분탐색 하다가 target 값 이상인 left 값이 타겟값을 넘는 첫 위치다.

Upper  Bound

const upperBound =(arr, target)=>{
    let left = 0;
    let right = arr.length - 1;

    while(left < right){
        let mid = Math.floor((left+right)/2);

        if(arr[mid] <= target){
            left = mid + 1;
        }else{
            right = mid;
        }
    }
    return left;
}
  • upper bound 는 배열에서 타겟값보다 큰 값이 나타나는 첫 위치를 찾는다.
  • 타겟값을 초과하는 인덱스를 반환한다.

이분탐색 vs lower, upper

  • 이분탐색은 탐색값을 찾는것 이므로 while의 조건이 left<=right다.
  • lower, upper 는 탐색값의 바운더리를 찾는 것 이므로 while의 조건이 left < right다.
반응형

'Language > Javascript' 카테고리의 다른 글

코딩테스트를 위한 PriorityQueue  (1) 2024.10.31
[JS] 프로토타입  (0) 2024.09.29
반응형

프론트엔드 개발자는 가끔 자바스크립트로 문제를 풀어야한다. 하지만, 애처롭게도 흔하디 흔한 우선순위큐는 내장되어있지 않다. 따라서, 우리는 우선수위큐를 "직접" 만들어야한다. 우선순위큐에 대해 알아보자

우선순위 큐

생성자

constructor(){
    this.heap = [];
}
  • heap 배열을 초기화하는 생성자다.

삽입 enqueue

  enqueue(value){
    this.heap.push(value);
    this._heapifyUp();
  }
  • heap 배열에 value를 push하고 힙정렬을 진행한다.

삭제 dequeue

dequeue(){
    const min = this.heap[0];
    const end = this.heap.pop();

    if(this.heap.length > 0){
      this.heap[0] = end;
      this._heapifyDown();
    }

    return min;
}
  • 삭제하려는 값은 맨위의 최소값이므로 (현재 코드는 최소힙을 기준으로 작성) 0번째 인덱스와 마지막인덱스를 교환한다.
  • 다시 힙정렬을 진행한다.

heapifyUp() 위쪽으로 재정렬

_heapifyUp() {
    let index = this.heap.length -1;
    const element = this.heap[index];

    while(index > 0){
       //우선순위큐는 이진트리를 기반으로 하기때문에 
       //parentIndex 는 자식 노드의 인덱스에 절반과 비슷하다.
      const parentIndex = Math.floor((index - 1) /2 );
      const parent = this.heap[parentIndex];
        //부모보다 크기때문에 최소힙 성립
      if(element >= parent) break;
        //그렇지 않으면 부모와 자리바꾸기
      this.heap[index] = parent;
      index = parentIndex;
    }
    this.heap[index] = element;
 }
  • 값을 삽입하면 오름차순으로 정렬해야한다. (삽입한 값이 맨뒤에 있다.)
  • 삽입된 위치(index) 값부터 (heap 배열에 push 했으므로 맨끝값) 부모 노드를 탐색하면서 바꿀 값을 찾는다.

heapifyDown() 아래쪽으로 재정렬

_heapifyDown(){
    let index = 0;
    const length = this.heap.length;
    const element = this.heap[0];

    while(true){
    //자식 인덱스를 확인
      let leftChildIndex = 2 * index + 1;
      let rightChildIndex = 2 * index + 2;
      let swapIndex = null;
    //왼쪽자식부터 부모가 더 크다면 바꿔야할 인덱스로 판명
      if(leftChildIndex < length){
        if(this.heap[leftChildIndex] < element){
          swapIndex = leftChildIndex;
        }
      }
    //오른쪽자식
      if(rightChildIndex < length){
      //왼쪽을 안바꿔도되고(null), 오른쪽 자식의 값이 부모보다 작다면 바꿔야한다.
      //왼쪽을 바꿔도되고, 오른쪽 자식의 왼쪽 자식의 값보다 작다면 오른쪽 자식을 바꿔야한다.
        if(
          (swapIndex === null && this.heap[rightChildIndex] < element) ||
          (swapIndex !== null && this.heap[rightChildIndex] < this.heap[leftChildIndex])
        ){
          swapIndex = rightChildIndex;
        }
      }

    //바꿀게없다면 패스
      if(swapIndex === null) break;
    //부모와 자식을 바꾼다.
      this.heap[index] = this.heap[swapIndex];
      index = swapIndex;
    }

    this.heap[index] = element;
  }
  • dequeue 를 하게 되면 맨위에 값이 최대값으로 바뀌기 때문에 자식을 탐색하면서 정렬해야한다.

전체 코드

class PriorityQueue{
  constructor(){
    this.heap = [];
  }

  enqueue(value){
    this.heap.push(value);
    this._heapifyUp();
  }

  dequeue(){
    const min = this.heap[0];
    const end = this.heap.pop();

    if(this.heap.length > 0){
      this.heap[0] = end;
      this._heapifyDown();
    }

    return min;
  }

  _heapifyUp() {
    let index = this.heap.length -1;
    const element = this.heap[index];

    while(index > 0){
      const parentIndex = Math.floor((index - 1) /2 );
      const parent = this.heap[parentIndex];

      if(element >= parent) break;

      this.heap[index] = parent;
      index = parentIndex;
    }
    this.heap[index] = element;
  }

  _heapifyDown(){
    let index = 0;
    const length = this.heap.length;
    const element = this.heap[0];

    while(true){
      let leftChildIndex = 2 * index + 1;
      let rightChildIndex = 2 * index + 2;
      let swapIndex = null;

      if(leftChildIndex < length){
        if(this.heap[leftChildIndex] < element){
          swapIndex = leftChildIndex;
        }
      }

      if(rightChildIndex < length){
        if(
          (swapIndex === null && this.heap[rightChildIndex] < element) ||
          (swapIndex !== null && this.heap[rightChildIndex] < this.heap[leftChildIndex])
        ){
          swapIndex = rightChildIndex;
        }
      }

      if(swapIndex === null) break;

      this.heap[index] = this.heap[swapIndex];
      index = swapIndex;
    }

    this.heap[index] = element;
  }
}
반응형

'Language > Javascript' 카테고리의 다른 글

코딩테스트를 위한 이분탐색  (1) 2024.11.09
[JS] 프로토타입  (0) 2024.09.29
반응형

자바스크립트는 프로토타입 기반의 객체 지향 언어

19.1 객체지향 프로그래밍

추상화 : 다양한 속성 중 프로그램에 필요한 속성만 간추려 내어 표현

const person = {
    name : 'Lee',
    address : 'Seoul'
};

객체 는 속성과 동작을 하나의 단위로 구성한 복합적인 자료구조

 

19.2 상속과 프로토타입

상속 객체의 프로퍼티나 메소드를 다른 객체가 그대로 사용할 수 있는 것

프로토 타입을 사용하는 이유

  • 인스턴스가 동일한 메소드를 중복 소유해 메모리를 불필요하게 낭비하는것을 막기 위해
function Circle(radius){
    this.radius = radius;
}

//생성자 함수에 프로토타입이 바인딩 되어있어 접근할 수 있다.
Circle.prototype.getArea = function() { return Math.PI * this.radius ** 2};

생성자와 프로토타입을 나누어 사용한다는 것은 생성자의 데이터 타입을 상속받는 프로토타입 객체라고 생각할 수 있다.

 

19.3 프로토타입 객체

모든 객체는 [[Prototype]] 내부 슬롯을 가진다.

1. __ proto __ 접근자 프로퍼티

모든 객체는 __ proto __ 접근자 프로퍼티를 통해 자신의 프로토타입 내부 슬롯에 간접적으로 접근할 수 있다.

  • 내부슬롯은 property가 아니기 때문에 직접 접근이 불가하고, 값과 메소드에 간접 접근가능하다.

__ proto __ 접근자 프로퍼티는 상속을 통해 사용된다.

  • __ proto __ 는 Object.prototype의 프로퍼티다. 모든 객체는 object를 상속해 프로토타입에 접근할 수 있다.

프로토타입 체인

  • 서로가 자신의 프로토타입일 때 발생한다.

__ proto __ 코드 내에서 직접 사용하는 것을 권장하지 않는다.

  • Object를 직접상속받지 않는 객체를 만들 수 있기에 프로퍼티를 사용할 수 없는 경우 존재한다.

2. 함수 객체의 prototype 프로퍼티

함수 객체만이 소유하는 prototype 프로퍼티는 생성자 함수가 생성할 인스턴스의 프로토타이블 가리킨다.

  • 화살표 함수와 ES6 메서드 축양 표현으로 정의한 메서드는 prototype 프로퍼티를 소유하지 않는다.
function Person(name) {this.name =  name;}

const me = new Person('Choi');

console.log(Person.prototype === me.__proto__); //true

3. 프로토타입의 constructor 프로퍼티와 생성자 함수

모든 프로토타입은 생성자 프로퍼티를 갖는다.

function Person(name) {this.name =  name;}

const me = new Person('Choi');

console.log(Person === me.constructor); //true

 

19.4 리터럴 표기법에 의해 생성된 객체의 생성자 함수와 프로토타입

리터럴 표기법에 의한 객체 생성 방식과 같이 명시적으로 new 연산자와 함께 생성자 함수를 호출하여 인스턴스를 생성하지 않는 객체 생성 방식도 있다.

//객체 리터럴로 생성된 객체
const obj = {};

//obj 객체의 생성자는 obj가 아닌 Object 생성자 함수
console.log(obj.constructor === Object); // true
  • 객체 리터럴로 생성된 객체가 부모 객체의 constructor을 꼭 가리키지 않는다.\
  • 생성자함수에 인수를 전달않거나 null로 전달하면 Object.prototype을 갖는 빈 객체를 생성한다.

Function 생성자로 만든 함수는 렉시컬 스코프를 만들지 않고 전역 함수인 것처럼 스코프를 생성하며 클로저도 만들지 않는다.

 

19.5 프로토타입의 생성 시점

프로토 타입은 생성자 함수가 생성되는 시점에 더불어 생성된다.

1. 사용자 정의 생성자 함수와 프로토타입 생성 시점

constructor 는 함수 정의가 평가되어 함수 객체를 생성하는 시점에 프로토타입도 더불어 생성된다.

console.log(Person.prototype);// {constructor f}

//생성자 함수
function Person(name) { this.name = name;}

생성자 함수로 만든 객체이기에 프로토타입이 동시에 만들어짐

const Person = name => { this.name = name; }

console.log(Person.prototype);// undefined

화살표함수는 non-constructor 이기에 프로토타입이 생성되지 않는다.

2. 빌트인 생성자 함수와 프로토타입 생성 시점

빌트인함수 : Object, String 등과 같은 함수

빌트인 함수도 생성자 함수가 생성되는 시점에 프로토타입이 생성된다.

객체가 생성되기 이전에 생성자 함수와 프로토타입은 이미 객체화되어 존재한다. 생성자 함수또는 리터럴 표기법으로 객체를 생성하면 프로토타입은 생성된 객체의 [[Prototype]] 내부슬롯에 할당된다.

 

19.6 객체 생성 방식과 프로토타입의 결정

객체생성방식

  • 객체 리터럴
  • Object 생성자 함수
  • 생성자 함수
  • Object.create 메서드
  • 클래스

-> OrdinaryObjectCreate (추상연산) 에 의해 객체가 생성된다는 공통점

프로토타입은 추상연산에 전달되는 인수에 의해 결정된다.

1. 객체 리터럴에 의해 생성된 객체의 프로토타입

const obj = { x: 1};

해당 객체 리터럴은 추상연산 이후에 Object.prototype , Object 생성자 함수와 서로서로 연결된다.

2. Object 생성자 함수에 의해 생성된 객체의 프로토타입

Object 생성자 함수를 호출하면 추상연산이 호출되고, 추상연산에 프로토타입 Object.prototype이 전달된다.

const obj = new Object();
obj.x = 1;

//Object 함수에 의해 생성된 obj 객체는 Object.prototype을 상속받는다.
console.log(obj.constructor === Object)//true
  • Object 함수 생성 방식은 빈객체를 생성하고 프로퍼티를 넣어야한다.

3. 생성자 함수에 의해 생성된 객체의 프로토타입

function Person(name) { this.name = name; }

const me = new Person('Choi');

new 연산자와 함께 생성자함수를 호출하면 추상연산이 수행된다.
추상연산에 의해 전달되는 프로토타입은 생성자 함수에 바인딩 되어있는 객체다.

 

19.7 프로토타입 체인

프로토타입 체인

자바스크립트는 프로토타입이 없는 객체의 프로토타입을 찾을 때 부모역할 프로토타입의 프로퍼티를 순차적으로 검색한다.

-> 자바스크립트가 객체지향 상속을 구현하는 메커니즘

(반대) 스코프 체인 : 프로퍼티가 아닌 식별자를 찾는 체인

Object.prototype 을 프로토타입 체인의 종점이라고 한다.

 

19.8 오버라이딩과 프로퍼티 섀도잉

const Person = (function () {
    //constructor
    function Person(name) { this.name = name;}

    //Prototype Method
    Person.prototype.sayHello = function () {
        console.log("Hi");
    }

    //Return Constructor Function
    return Person;
}());

const me = new Person('Choi');

//Instance Method
//Property Shadowing
me.sayHello = function () {
    console.log("Hey");
}

me 객체의 sayHello 생성으로 인해 prototype의 sayHello 는 프로퍼티 섀도잉 됐다.

delete me.sayHello;

me.sayHello();
  • 인스턴스 메소드는 삭제가 되지만, 프로토타입의 메소드는 삭제되지 않는다.

 

19.9 프로토타입의 교체

부모객체인 프로토타입을 동적으로 변경할 수 있다.

1. 생성자 함수에 의한 프로토타입의 교체

const Person = (function () {
    //constructor
    function Person(name) { this.name = name;}

    //Prototype Method
    Person.prototype = {
        sayHello() {
            console.log(`Hi`);
        }
    }

    //Return Constructor Function
    return Person;
}());

prototype 을 객체리터럴로 교체하면 prototype의 constructor 는 사라진다.

  • 생성자 함수를 객체리터럴에 추가하면 constructor 는 복구된다.

const Person = (function () {
    //constructor
    function Person(name) { this.name = name;}

    //Prototype Method
    Person.prototype = {
        consturctor: Person,
        sayHello() {
            console.log(`Hi`);
        }
    }

    //Return Constructor Function
    return Person;
}());

2. 인스턴스에 의한 프로토타입의 교체

function Person(name){
    this.name = name;
}

const me = new Person('Choi');

const Parent = {
    constructor: Person,
    sayHello() {
        console.log("Hi");
    }
}

Person.prototype = parent;

Object.setPrototypeOf(me, parent);

인스턴스로 프로토타입을 재정의 할때 constructor 역시 만들어줘야 생긴다.

19.10 instanceof 연산자

instanceof
좌변에 객체를 가리키는 식별자, 우변에 생성자 함수를 가리키는 식별자를 피연산자로 받는다.

객체 instanceof 생성자 함수

생성자 함수의 prototype에 바인딩된 객체가 프로토타입 체인 상에 존재하는지 확인

function Person(name) { this.name = name; }

const me = new Person('Choi');

console.log(me instanceof Person); // true

//프로토타입 교체를 한다.
const parent = {};

Object.setPrototypeOf(me, parent);

//프로토타입 교체를 통해 me의 프로토타입은 Person이 아니므로 거짓이 나온다.
console.log(me instanceof Person); // false;

프로퍼티와 생성자 함수간의 연결이 파괴되어도 instanceof는 아무런 영향을 받지 않는다. (프로토타입 체인)

19.11 직접 상속

1. Object.create에 의한 직접 상속

Object.create 는 추상연산을 호출한다.

let obj = Object.create(Object.prototype, { x: {value:1});

장점

  • new 연산자없이 객체생성 가능
  • 프로토타입 지정하면서 객체 생성 가능
  • 객체 리터럴에 의해 생성된 객체도 상속받을 수 있다.

주의

let obj = Object.create(null);

프로토타입의 종점에 위치하는 객체이기에 Object 빌트인 메소드를 사용할 수 없다. (.toString() ...)

2. 객체 리터럴 내부에서 __ proto __ 에 의한 직접 상속

const myProto = {x:10};

//myProto 를 상속받는 obj
const obj = {
    y: 20,
    __proto__: myProto
}

 

19.12 정적 프로퍼티 / 메서드

static 프로퍼티 / 메서드는 생성자 함수로 인스턴스를 생성하지 않아도 참조/ 호출할 수 있는 프로퍼티 /메서드

function Person(name) { this.name = name;}

Person.prototype.sayHello = function () { console.log(`Hi`);};

Person.staticMethod = function () { console.log(`static Hi`)};

const me = new Person('Choi');

//생성자 함수에 추가한 함수
Person.staticMethod()

//생성자 함수가 아니기에 에러
me.staticMethod() //TypeError

 

19.13 프로퍼티 존재 확인

1. in 연산자

key in object

const person = {name = 'Lee'};

console.log('name' in person )//true

상속 받는 모든 프로토타입의 프로퍼티를 확인하므로 주의해야한다.

console.log('toString' in person) //true

has (ES6)

console.log(Reflect.has(person, 'name')); //true

2. Object.prototype.hasOwnProperty 메서드

프로퍼티 키가 객체의 고유 값인 경우에만 반환

console.log(person.hasOwnProperty('name')) // true

console.log(person.hasOwnProperty('toString')) // false

 

19.14 프로퍼티 열거

1. for... in 문

const test = {a : 1, b : 1};

for(const key in test) {
    console.log(key);
}

for...in 문은 객체의 프로토타입 체인 상에 존재하는 모든 프로토타입 프로퍼티 중에서 프로퍼티 어트리뷰트의 값이 true 인 프로퍼티를 순회하며 열거

2. Object.keys/values/entries 메서드

객체 자신만의 고유 프로퍼티만 열거하기 위해서 사용

const person = {
    name: 'Lee',
    addr: 'Seoul',
    __proto__: {age : 20}
};

console.log(Object.keys(person)); //["name", "addr"];
반응형

'Language > Javascript' 카테고리의 다른 글

코딩테스트를 위한 이분탐색  (1) 2024.11.09
코딩테스트를 위한 PriorityQueue  (1) 2024.10.31
반응형

형변환

명시적 형변환

int i = 300;
byte b = (byte) i; // 값 손실 발생

묵시적 형변환

byte b = 10;
int i = b; // 값 손실 없음

배열 선언

1차원 배열

int points[] = new int[3];

2차원 배열

int[][] intArray = new int[4][];

문자열을 문자 배열로 변환

String a = new String("123");
char[] charArray = a.toCharArray();

UML

  • private: 빨간색
  • protected: 노란색
  • public: 녹색
  • default: 파란색

객체지향 프로그래밍

특징

  1. 추상화
  2. 다형성
  3. 상속
  4. 데이터 은닉과 보호

객체와 클래스

  • 객체: 클래스를 데이터 타입으로 메모리에 생성되어 실제로 동작하는 것
  • 클래스: 객체를 정의해 놓은 것

생성자

Person person = new Person();
Person person = new Person("name");

this 키워드

  • 객체 자신을 가리킴
  • 로컬 변수와 멤버 변수를 구분할 때 사용
public Person(String name) {
    this.name = name;
}

public Person() {
    this("name");
}

상속

public class Child extends Parents

단일 상속

  • 자바는 단일 상속만 지원 (다이아몬드 상속 문제 방지)

오버라이딩

public class Person {
    void kick() {
        // 차다.
    }
}

public class Player extends Person {
    @Override
    void kick() {
        // 공을 차다
    }
}

조건

  • 메서드 이름, 매개변수, 리턴 타입 동일
  • 접근 제한자는 부모와 같거나 더 넓어야 함
  • 부모보다 더 큰 예외는 던질 수 없음

접근 제한자

  1. public: 모든 클래스에서 접근 가능
  2. protected: 동일 패키지 또는 상속 관계의 클래스에서 접근 가능
  3. private: 동일 클래스 내에서만 접근 가능 (캡슐화)
  4. default: 동일 패키지 내의 클래스에서만 접근 가능

Singleton 패턴

public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

다형성

  • 하나의 객체가 여러 형태를 가질 수 있는 성질
public void println(Object o) {}
public void println(Person p) {}

제네릭

정의

  • 다양한 타입의 객체를 다루는 메서드, 컬렉션 클래스에서 컴파일 시 타입 체크
public interface Interface_name<T> {}

형인자

  • T: 타입
  • E: 요소
  • K: 키
  • V: 값

주의할 점

  1. 프라이미티브 타입 사용 불가
  2. 타입 캐스팅 시 런타임에 타입 정보 유지되지 않음
  3. 정적 컨텍스트에서 제네릭 사용 불가
  4. 제네릭 배열 생성 불가
  5. 제네릭 타입 인스턴스 생성 불가

자바의 와일드카드 자료형

와일드카드(Wildcard): 불특정 타입을 나타내기 위해 사용 (?)

  1. 무제한 와일드카드 (?): 어떤 타입이라도 허용
  2. 상한 경계 와일드카드 (? extends T): 특정 타입이나 그 하위 타입을 허용 (읽기 전용)
  3. 하한 경계 와일드카드 (? super T): 특정 타입이나 그 상위 타입을 허용 (쓰기 전용)

Collection 프레임워크

컬렉션(Collection): 여러 개의 객체를 모아서 관리하는 자바의 프레임워크

주요 인터페이스

  1. Collection: 컬렉션의 기본 인터페이스
  2. List: 순서가 있는 컬렉션, 중복 허용 (ArrayList, LinkedList)
  3. Set: 순서가 없는 컬렉션, 중복 불가 (HashSet, TreeSet)
  4. Queue: FIFO 방식의 컬렉션 (LinkedList, PriorityQueue)
  5. Map<K, V>: 키-값 쌍으로 이루어진 컬렉션 (HashMap, TreeMap)

주요 구현 클래스

  1. ArrayList: 가변 크기 배열, 빠른 인덱스 접근
  2. LinkedList: 이중 연결 리스트, 빠른 삽입/삭제
  3. HashSet: 해시 테이블, 중복 불가
  4. TreeSet: 이진 검색 트리, 정렬된 순서 유지
  5. HashMap: 해시 테이블, 키 중복 불가, 값 중복 가능

정렬 (Sort)

자바에서 배열이나 컬렉션을 정렬하는 방법

1. 배열 정렬

Arrays.sort() 메서드

  • 기본형 배열 정렬
    int[] numbers = {5, 3, 8, 1, 2};
    Arrays.sort(numbers);
  • 객체 배열 정렬
    String[] names = {"John", "Alice", "Bob"};
    Arrays.sort(names);
  • Comparator를 사용한 정렬
    Arrays.sort(names, (s1, s2) -> s2.compareTo(s1));

2. 컬렉션 정렬

Collections.sort() 메서드

  • List 정렬
  • List<Integer> numberList = Arrays.asList(5, 3, 8, 1, 2); Collections.sort(numberList);
  • 객체 List 정렬 (Comparable 사용)
  • public class Person implements Comparable<Person> { private String name; private int age; @Override public int compareTo(Person other) { return this.age - other.age; } } List<Person> people = Arrays.asList(new Person("John", 25), new Person("Alice", 30)); Collections.sort(people);
  • Comparator를 사용한 정렬
  • Collections.sort(people, (p1, p2) -> p1.name.compareTo(p2.name));

3. 스트림을 사용한 정렬 (Java 8 이상)

  • 기본 정렬
  • List<Integer> numberList = Arrays.asList(5, 3, 8, 1, 2); List<Integer> sortedList = numberList.stream().sorted().collect(Collectors.toList());
  • Comparator를 사용한 정렬
  • List<Person> sortedPeople = people.stream() .sorted(Comparator.comparing(Person::getName)) .collect(Collectors.toList());

람다 표현식 (Lambda Expressions)

람다 표현식: 익명 함수를 간결하게 표현하는 방법

문법

(parameters) -> expression
(parameters) -> { statements; }

람다식 정렬

List<String> list = Arrays.asList("B", "A", "C");
Collections.sort(list, (s1, s2) -> s1.compareTo(s2));

List<Person> people = Arrays.asList(new Person("John"), new Person("Alice"));
Collections.sort(people, (p1, p2) -> p1.getName().compareTo(p2.getName()));

스트림 (Stream)

스트림(Stream): 컬렉션을 처리하는 함수형 프로그래밍 API

주요 특징

  • 연속된 요소: 컬렉션의 요소를 하나씩 처리
  • 함수형 스타일: 선언적이고 함수형 프로그래밍 스타일
  • 지연 연산: 최종 연산 시에만 중간 연산 수행
  • 무상태 연산: 각 요소를 독립적으로 처리

스트림 원리

  • 파이프라인: 소스 -> 중간 연산 -> 최종 연산
  • 중간 연산: 지연 연산, 최종 연산 시 수행

스트림 연산 예시

  • 스트림 생성
  • List<String> names = Arrays.asList("John", "Alice", "Bob"); Stream<String> stream = names.stream();
  • 중간 연산 (필터링, 변환, 정렬)
  • List<String> filteredNames = names.stream() .filter(name -> name.startsWith("A")) .collect(Collectors.toList());
  • 최종 연산 (반복, 집계)
  • names.stream().forEach(name -> System.out.println(name));
    long count = names.stream().filter(name -> name.startsWith("A")).count();
---

### 예외처리 (Exception Handling)

**예외처리**: 예외 상황을 처리하여 프로그램의 비정상 종료를 방지

### 주요 개념과 키워드

1. **try 블록**
   - 예외가 발생할 가능성이 있는 코드 포함
   ```java
   try {
       // 예외 발생 가능 코드
   }
  1. catch 블록
    • 예외가 발생하면 처리
      try {
        // 예외 발생 가능 코드
      } catch (ExceptionType e) {
        // 예외 처리 코드
      }
  2. finally 블록
    • 예외 발생 여부와 관계없이 항상 실행
      try {
        // 예외 발생 가능 코드
      } catch (ExceptionType e) {
        // 예외 처리 코드
      } finally {
        // 항상 실행되는 코드
      }
  3. throw 키워드
    • 명시적으로 예외 발생
      throw new ExceptionType("예외 메시지");
  4. throws 키워드
    • 메서드가 특정 예외를 던질 수 있음을 선언
      public void myMethod() throws ExceptionType {
        // 예외 발생 가능 코드
      }

예외 계층 구조

  • Checked Exception: 컴파일 시점에서 반드시 처리해야 하는 예외 (IOException, SQLException)
  • Unchecked Exception: 런타임 시점에서 발생하는 예외 (NullPointerException, ArrayIndexOutOfBoundsException)

파일 입출력 (File I/O)

파일 입출력: 파일을 읽고 쓰는 작업

주요 클래스 및 인터페이스

  1. java.io 패키지
    • File: 파일 및 디렉토리 경로명 표현
    • FileReader: 파일을 문자 스트림으로 읽음
    • FileWriter: 파일을 문자 스트림으로 씀
    • BufferedReader: 문자 입력 스트림을 버퍼링하여 효율적으로 읽음
    • BufferedWriter: 문자 출력 스트림을 버퍼링하여 효율적으로 씀
    • FileInputStream: 파일을 바이트 스트림으로 읽음
    • FileOutputStream: 파일을 바이트 스트림으로 씀

기본적인 파일 읽기 및 쓰기 예제

문자 스트림

  • 파일 쓰기 (FileWriter)
  • try (FileWriter writer = new FileWriter("example.txt")) { writer.write("Hello, world!"); } catch (IOException e) { e.printStackTrace(); }
  • 파일 읽기 (FileReader)
  • try (FileReader reader = new FileReader("example.txt")) { int data; while ((data = reader.read()) != -1) { System.out.print((char) data); } } catch (IOException e) { e.printStackTrace(); }

바이트 스트림

  • 파일 쓰기 (FileOutputStream)
  • try (FileOutputStream output = new FileOutputStream("example.bin")) { output.write("Hello, world!".getBytes()); } catch (IOException e) { e.printStackTrace(); }
  • 파일 읽기 (FileInputStream)
  • try (FileInputStream input = new FileInputStream("example.bin")) { int data; while ((data = input.read()) != -1) { System.out.print((char) data); } } catch (IOException e) { e.printStackTrace(); }

컴파일 에러

int i;
System.out.println(i); // 초기화 안한 컴파일 오류

런타임 에러

String s = null;
System.out.println(s.length()); // NullPointerException

Teacher t = (Teacher) person; // ClassCastException

Call By Value

String s = new String("hello");
s.concat("world");
System.out.println(s); // hello

s = s.concat("world");
System.out.println(s); // helloworld

인터페이스 VS 추상클래스

  인터페이스 추상클래스
공통점 추상화: 구체적인 구현 없이 메서드 선언만 포함 가능
다형성 지원: 여러 클래스가 공통된 인터페이스나 추상 클래스를 구현함으로써 동일한 타입으로 다룰 수 있음
상속 가능
차이점 구현된 메서드 포함 가능, 필드 가질 수 있음, 생성자 포함 구현 포함 안함 (default 메서드는 예외), 필드 가질 수 없음
단일 상속 다중 상속
extends implements
공통된 기능을 공유하면서 일부 메서드의 구체적인 구현을 제공하기 위해 사용 클래스 간의 계약을 정의하고, 클래스가 반드시 구현해야 하는 메서드를 명시하기 위해 사용

List vs Set vs Map

List

  • 입력 순서가 있는 데이터의 집합
  • 순서가 있으므로 데이터 중복 허용
  • 구현 클래스: ArrayList, LinkedList

Set

  • 입력 순서를 유지하지 않는 데이터의 집합
  • 순서가 없으므로 데이터를 구별할 수 없음
  • 중복 불가
  • 구현 클래스: HashSet, TreeSet

Map

  • Key, Value의 쌍으로 데이터를 관리하는 집합
  • 순서는 없고 Key의 중복 불가, Value 중복 가능
  • 구현 클래스: HashMap, TreeMap
반응형

+ Recent posts