0%

Generics

  • 대상 객체의 타입을 입력 받아서 사용하는 방식
  • 미리 사용할 수 있는 타입을 명시해서 컴파일 타임에 체크 가능
    • 입력을 Object로 할 수도 있으나, runtime에 instanceof 로 객체를 체크 해야 함
    • 제네릭을 사용할 경우 이러한 과정 없이 간결하게 코드 작성을 할 수 있다.

Generic Class

  • 클래스를 선언 할때는 설정되지 않은 타입이 있으며 이것을 타입 파라미터로 표현
1
2
3
4
5
6
7
8
9
class GenericFoo<T> { // T: type parameter
String name;
T memberVar;

public GenericFoo(String name, T memberVar) {
this.name = name;
this.memberVar = memberVar;
}
}
  • 여러개의 타입 파라미터 또한 가능
1
2
3
class HashMap<K,V> {

}
  • 인터페이스도 generic이 가능하다.
1
2
3
interface GenericInterface<T> {

}
  • Geneirc type 사용시 유의점

    • 문법적으로 문제가 있는 경우

      1
      2
      3
      4
      class Generic<T> {
      static T classVar; // -> T는 객체를 생성할 때 결정 되기 때문에 complie time에 T를 알 수 없다.
      static void mehtod(T varl) { } // 마찬가지 이유로 complie time에 T를 알 수 없음
      }
    • 문법적으로는 문제가 없을 것 같으나, 안정성 문제로 금지됨 -> 암기 요소

      1. Type parameter 의 instance를 생성하는 것은 불가능하다.
      2. Generic type parameter 에 대한 instance checking은 불가능하다.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    class Generic<T> {
    T memberVar = new T(); // -> 안정성 문제 때문에 불가능
    {
    Object obj = new Object();
    if (obj instanceof T) { // not possible instance 체크 불가능

    }
    }
    }

Inheritance of Generic Type

  • 타입 파라미터는 부모 제네릭 타입 파라미터를 모두 채워줘야 함
  • 추가적인 타입 파라미터도 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
class GFoo<T> {

}

interface IGFoo<D> {

}

class IGIFooTwo<K, T, D> extents GFoo<T> implements IGFoo<D> {

}
  • 부모 클래스 / 인터페이스들에 동일한 타입 파라미터를 넘겨줄 수 있다.
1
2
3
class IGIFoo<T> extends GFoo<T> implements IGFoo<T> {

}
  • 타입 제한을 하지 않으면 extends Object와 동일하다.
1
class GenericNoTypeLimit<T extends Object> {}
  • extends를 이용해서 부모 클래스를 제한 할 수 있다.
1
2
                                                // interface upper limit
class GenericTypeLimitation<T extends Number & Clonable> {}

Generic Method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class GenericMethod {
public static <T> T staticMethod(T t) {
return t;
}
public int method(int x) {
return x;
}
public <T> T method(int x) {
return x;
}
public <T> T method(T x) {
return x;
}
}

Wild Card

  • Wild Card ? 는 method 의 입력 타입에 Generic 이 쓰일 경우, Generic 의 타입 변수를 제한 할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class WildFoo {

}

class WildBar extends WildFoo {

}

class WildGeneric<T> {

}

class WildCard {
public <T> void method(WildGeneric<T> x) {}
public void mehtod1(WildGeneric<?> x) {} // T, ?의 차이점: super 키워드를 사용하여 상한을 정할 수 있다.
public void method1_eq(WildGeneric<? extends Object> x) {} // Object가 상한
public void method2(WildGeneric<? extends WildFoo> x) {} // WildFoo, WildBar 상한
public void method3(WildGeneric<? super WildBar> x) {} // Object, WildFoo, WildBar, 하한
}

Dynamic Binding: JIT Complie

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class GenericMethod {
public static <T> T staticMethod(T t) {
return t;
}
public int method(int x) {
return x;
}
public <T> T method(int x) {
return x;
}
public <T> T method(T x) {
return x;
}
}

public class Generics {
public static void main(String[] args) {
// Dynamic binding: behavior of method defined on runtim with JIT complication
GenericMethod.staticMethod("abcde");
GenericMethod.staticMethod(12345);
}
}

Wrapper Class

  • 기본형 타입을 객체로 쓰기 위해 있는 클래스
  • 기본형 타입이 허용되지 않는 문법에 기본형 타입을 쓰기 위해서 제공
1
2
3
4
5
public static Integer add(Integer x, Integer y) {
return x + y;
// 자동으로 기본 자료형으로 변형 및 계산
// 반환시 다시 Autoboxing이 이루어짐
}
  • 여러가지 선언 방법들
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Integer integer = new Integer(10);
Interger integer1 = Integer.valueOf(10);

Charactor character = new Character('d');
Charactor character1 = Character.value('f');

// Autoboxing
Integer integer2 = 4;

// 문자열 <-> 기본자료형
int x = Integer.parseInt("100");
int y = new Integer("100");
int z = Integer.valueOf("200");

int m = new Integer(10); // 기본 자료형이 필요한 자리에 Wrapper class가 있을 경우 unboxing이 일어난다

다형성 (Polymorphism)

다형성의 특징

  • 부모 클래스 타입으로 자식 클래스 객체를 참조하는 특징
1
2
3
4
5
6
7
8
9
10
11
public class Foo {
public void methodA() {
return;
}
}

public class Bar extends Foo {
public void methodB() {
return;
}
}
  • 부모 클래스로 자식 클래스를 참조한 경우, 자식 클래스의 메소드는 사용할 수 없다.
1
2
3
4
5
6
7
8
9
public class Main {
public static void main(String args[]) {
Bar bar = new Bar();
Foo foo = (foo)bar;

foo.methodA(); // works
// foo.methodB(); // error
}
}
  • 자식 클래스로 부모 클래스를 참조하려 하면 java.lan.ClassException 오류 발생
1
2
3
4
5
6
7
8
9
10
11
public class Main {
public static void main(String args[]) {
Foo foo = new Foo();
Bar bar;

// bar = (Bar)foo;
if (foo instanceof Bar) { // false
bar = (Bar)foo;
}
}
}
  • Method overriding은 메모리상의 객체의 타입을 따른다. (Virtual method call)
  • 멤버 변수의 재정의는 선언된 객체의 타입을 따른다. (문법적으로 본다)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Foo {
public String x = "Super";

public void methodA() {
System.out.println("Super");
}
}

public class Bar extends Foo {
public String x = "Sub";

@override
public void methodA() {
System.out.println("Sub");
return;
}
}

public class Main {
public static void main(String args[]) {
Bar bar = new Bar();
Foo foo = (Foo)bar;

System.out.println(bar.x); // Sub
bar.methodA(); // "Sub"

System.out.println(foo.x); // Super
foo.methodA(); // Virtual method call
}
}
  • Covariant return type
1
2
3
4
5
6
7
8
9
10
11
class Foo {
public Foo getInstance() {
return this;
}
}

class Bar extends Foo {
public Bar getInstance() { // Foo 대신 Bar로 리턴 가능
return this;
}
}

추상 클래스 (Abstract Class)

  • 일부 메소드가 구현되지 않고 선언만 되어 있는 클래스
    • 자식 클래스에서 반드시 구현해야 하는 메소드를 abstract로 선언
    • 필요한 클래스가 모두 구현될 수 있도록 강제

추상 클래스의 선언

  • abstract 키워드를 이용해 class를 선언
  • abstract 키워드를 이용해 abtract 키워드를 이용해 method를 선언
1
2
3
4
5
6
7
abstract class AbstractFoo {
public void method() {
return;
}

public abstract void abstractMethod();
}

Data Manipulation Language, DML

  • SELECT - 검색
  • INSERT - 등록
  • UPDATE - 수정
  • DELETE - 삭제

SELECT

1
SELECT(DISTINCT) {column_name} (ALIAS) FROM {table_name};
SELECT 검색하고자 하는 데이터(column)를 나열
DISTINCT 중복행을 제거
ALIAS 나타날 컬럼에 대한 다른 이름 부여
FROM 선택한 컬럼이 있는 테이블을 명시한다

Select Examples

  • Search whole data
1
SELECT * FROM DEPARTMENT;
  • Search certain column
1
SELECT empno, name, job from employee;
  • Put alias to column
1
SELECT empno as 사번, name as 이름, job as 직업 from employee;

or

1
SELECT empno 사번, name 이름, job 직업 from employee;
  • Column concatenation
    • using concat func
1
SELECT concat(empno, '-', deptno) AS '사번-부서번호' FROM employee;
  • Removing redundant row
1
SELECT DISTINCT deptno FROM employee;
  • Using ORDER BY
1
SELECT(DISTINCT) {column_name} ((as) ALIAS) FROM {table_name} ORDER BY {column_name} (ASC, DESC)
ASC by asending order (default)
DESC by desending order
1
SELECT empno, name, job FROM employee order by name desc;
  • Using WHERE
1
2
SELECT(DISTINCT) {column_name} FROM {table_name} WHERE {contidion}
ORDER BY {column_name or statement} (ASC, DESC)
1
SELECT name, hiredate, FROM employee WHERE hiredate < '1981-01-01';
1
2
3
4
SELECT name, deptno FROM employee WHERE deptno in (10, 30);
SELECT name, deptno FROM employee WHERE deptno = 10 or deptno = 30;
SELECT * from employee WHERE deptno = 10 and salary < 1500;
SELECT * from employee WHERE deptno = 30 and salary < 1500;
  • LIKE keyword

    • using wildcard to select pattern string
      • %: 0-9a-zA-Z several charactor
      • _: single charactor
    1
    SELECT * FROM employee WHERE name LIKE 'A%'
    1
    SELECT * FROM employee WHERE name like '_A%';
    1
    SELECT * FROM employee WHERE name like '%A%';
  • Using SQL function

    • UCASE, UPPER
    1
    SELECT UPPER('SEoul'), UCASE('seOUL`);
    • LCASE, LOWER
    1
    SELECT lower(name) FROM employee;
    • SUBSTRING

      1
      SELECT SUBSTRING('Happy Day', 3, 2);
    • LPAD, RPAD

      1
      SELECT LPAD('hi', 5, '?'), LPAD('joe', '7', '*');
    • TRIM, LTRIM, RTRIM

      1
      SELECT LTRIM(' hello '), RTRIM(' hello ');
    • ABS(x)

    • MOD(n, m)

  • CAST: type casting CAST(expression AS type)

  • Group function

    • COUNT()
    • COUNT(DISTINCT)
    • AVG()
    • MIN()
    • MAX()
    • SUM()
    • GROUP_CONCAT()
    • VARIANCE()
    • STDEV()
  • Using group function with group by clause

    1
    SELECT deptno, avg(salary), sum(salary) FROM employee GROUP BY deptno;

INSERT

1
2
INSERT INTO {table_name} (field1, field2, field3, ...)
VALUES (value_field1, value_field2, value_field3, ...)
  • The primary key must have value, since primary key cannot be set NULL value.

UPDATE

1
2
3
UPDATE {table_name}
SET field1 = value_field1, field2 = value_field2, field3 = value_field3 ...
WHERE {condition}
  • When WHERE condition is omitted, every row is affected by UPDATE statement.

DELETE

1
2
3
DELETE
FROM {table_name}
WHERE {condition}
  • Keep in mind that WHERE condition must be included unless you intend to delete all data.

JOIN

1
2
SELECT employee.name, department.name FROM employee
JOIN department ON employee.deptno = department.deptno;

Data Definition Language, DDL

Create Table

1
2
3
4
5
6
7
CREATE TABLE {table_name}(
field_name1 type [NULL | NOT NULL][DEFAULT][AUTO_ENCREMENT],
field_name2 type [NULL | NOT NULL][DEFAULT][AUTO_ENCREMENT],
field_name2 type [NULL | NOT NULL][DEFAULT][AUTO_ENCREMENT],
...
PRIMARY KEY (field_name)
)
  • Creating another employ table
1
DESC EMPLOYEE
Field Type Null Key Default Extra
empno int NO PRI NULL
name varchar(10) YES NULL
job varchar(9) YES NULL
boss int YES MUL NULL
hiredate varchar(12) YES NULL
salary decimal(7,2) YES NULL
comm decimal(7,2) YES NULL
deptno int YES MUL NULL
1
2
3
4
5
6
7
8
9
create table employee2 (
empno integer not null primary key,
name varchar(10),
job varchar(9),
boss integer,
hiredate varchar(12),
salary decimal(7,2),
comm decimal(7,2),
deptno integer);
  • Creating book table
1
2
3
4
CREATE TABLE book(
isbn varchar(10) primary key,
title varchar(20) not null,
price integer not null);

Alter Table

  • Add column field to table
1
2
ALTER TABLE {table_name}
ADD {field_name} type [NULL | NOT NULL][DEFAULT][AUTO_INCREMENT];
  • example

    1
    2
    ALTER TABLE book
    add author varchar(20) NOT NULL;
  • Delete column field on table
1
2
ALTER TABLE {table_name}
drop {field_name};
  • example

    1
    2
    ALTER table book
    DROP price;
  • Update column field (both its name and property)
1
2
ALTER TABLE {table_name}
CHANGE {old_field_name} {new_field_name} [NULL | NOT NULL][DEFAULT][AUTO_INCREMENT];
  • example

    1
    2
    Alter table employee2
    CHANGE deptno dept_no int(11);
  • Renaming Table
1
ALTER TABLE {old_table_name} rename {new_table_name}
  • example

    1
    ALTER TABLE employee2 rename employee3;

Drop Table

1
DROP TABLE {table_name};
  • If there is some relational dependencies between tables, it should be deleted in reverse order of creation.

Database and Database Management System (DBMS)

도서관의 책들이 데이터베이스 라고 한다면, 도서관 사서 또는 도서 정보를 찾아주는 컴퓨터를 DBMS
라고 할 수 있다.

Database

  • 데이터의 집합 (A Set of Data)
  • 여러 응용 시스템(프로그램)들의 통합된 정보들을 저장하여 운영할 수 있는 공용(share) 데이터의 집합
  • 효율적으로 저장, 검색, 갱신 할 수 있도록 데이터 집합들끼리 연관시키고 조직화 되어야 한다.

Feature of Database

  • Real-time Accessbility
    • 사용자 요구를 즉시 처리
  • Continuous Evolution
    • 정확한 값을 유지하려고 삽입, 삭제, 수정 작업등을 이용해 데이터를 지속적으로 갱신
  • Concurrent Sharing
    • 사용자마다 서로 다른 목적으로 사용하므로 동시에 여러 사람이 동일한 데이터에 접근하고 이용 할 수 있다.
  • Content Reference
    • 저장한 데이터 레코드의 위치나 주소가 아닌 사용자가 요구하는 데이터의 내용, 즉 데이터 값에 따라 참조 할 수 있어야 한다.

Database Management System (DBMS)

A database management system (DBMS) is a software package designed to define, manipulate,
retrieve and manage data in database. A DBMS generally manipulates the data itself, the data
format, field names, record structure and file structure. It also defines rules to validate and
manipulate this data.

  • 데이터베이스를 관리하는 소프트웨어
  • 여러 응용 소프트웨어(프로그램) 또는 시스템이 동시에 데이터베이스에 접근하여 사용할 수 있게 한다.
  • 필수 3기능
    • 정의기능: 데이터베이스의 논리적, 물리적 구조를 정의
    • 조작기능: 데이터를 검색, 삭제, 갱신, 삽입, 삭제 하는 기능
    • 제어기능: 데이터베이스의 내용 정확성과 안정성을 유지하도록 제어하는 기능
  • Oracle, SQL Server, MySQL, DB2 등의 상용 또는 공개 DBMS가 있음

데이터베이스 관리 시스템의 장/단점

  • 장점
    • 데이터 중복이 최소화
    • 데이터 일관성 및 무결성 유지
    • 데이터 보안 보장
  • 단점
    • 운영비가 비싸다
    • 백업 및 복구에 대한 관리가 복잡
    • 부분적 데이터베이스 손실이 전체 시스템을 정지

MySQL

  • Install

    $ brew install Mysql

  • Starting server

    $ mysql.server start

    • starting on deamon(using HomeBrew)

      $ brew service start mysql

    • restarting

      $ brew service restart mysql

    • listing

      $ brew services list

  • Exit MySQL

    $ mysql.server stop

    • Quiting on HomeBrew

      $ brew services stop mysql

SQL(Structured Query Language)

  • SQL은 데이터를 보다 쉽게 검색하고 추가, 삭제, 수정 같은 조작을 할 수 있도록 고안된 컴퓨터 언어
  • 관계형 데이터베이스에서 데이터를 조작하고 쿼리하는 표준 수단
  • DML(Data Manipulate Language): 데이터를 조작하기 위해서 사용, INSERT, UPDATE, DELETE, SELECT등
  • DDL(Data Definition Language): 데이터베이스의 스키마를 정의하거나 조작하기 위해 사용, CREATE, DROP, ALTER등
  • DCL(Data Control Language): 데이터를 제어하는 언어, 권한을 관리하고, 데이터의 보안, 무결성 등을 정의 GRANT, REVOKE등

Table

  • 우리와 SpreadSheet에서의 table과 유사한 개념
  • 데이터베이스는 table의 형태로 존재하는 것이 아님
  • table을 보려면 table을 생성하는 SQL을 사용해야함
  • 테이블에 앖을 저장하려면 저장하기 위한 SQL을 사용

Table의 구성요소

  • Table: RDBMS의 기본적 저장구조, 한 개 이상의 column과 0개 이상의 row로 구성
  • Column: 테이블 상에서의 단일 종류의 데이터를 나타냄, 특정 데이터 타입 및 크기를 가지고 있음
  • Row: Column들의 값의 조합, 레코드라고 불림, 기본키에 의해서 구분 되며 기본키는 중복을 허용하지 않고, 없어서는 안됨
  • Field: Row와 Column의 교차점으로 Field는 데이터를 포함할 수 있고 없을때는 NULL 값을 가지고 있음

Git Summary

git Process and command

git diagram

Set configuration

$ git config --global user.name "{github username}"
$ git config --global user.email "{github email address}"
$ git config --global core.editor "vim"
$ git config --global core.pager "cat"
$ git config --list
  • optional: $ git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

First Repo

$ mkdir first-repo && cd first-repo
$ git init
$ git remote add origin https://github.com/{username}/{reponame}.git
$ touch README.md
$ git add README.md
$ git commit -m "docs: Create README.md"
$ git push -u origin master # setting up stream

Basic workflow of git

$ git status
$ git add .
$ git commit
$ git push origin master

Commit Convention

  • 커밋 제목은 50자 이내
  • 제목과 내용사이 한칸
  • prefix를 사용하여 한눈에 커밋의 용도를 알기 쉽게 한다
    • feat: features
    • docs: documentations
    • conf: configurations
    • test: test
    • fix: bug-fix
    • refactor: refactoring
    • perf: Performance

vim key

  • A: append text at the end of the string
  • o: add line below
  • O: insert line above

Using Hexo: Blog posting

Dependencies

  1. git
  2. node.js
    npm install -g hexo-cli

Init Blog

$ npm install hexo-cli -g
$ hexo init blog
$ cd blog
$ npm install
$ hexo server

New Post

$ hexo new post "{file name}"
$ vi source/_posts/{file name}
$ `jot something`

Generate, test and deploy

$ hexo clean && hexo generate
$ hexo server // local run and check whether the article is generated and displayed well.
$ hexo deploy

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment