2017년 2월 22일 수요일

Thread와 Runable

Thread와 Runable 의 차이점을 어찌 시원하게 알려주는책이 없는거 같아 검색좀 때려봤다.

Thread :
    ThreadClass 의 method를 사용할수있음
    작업 대상의 Class가 다른 Class로 부터 상속받을경우(자식 Class일 경우) Thread가 사용 불가능함
왜냐면 이미 extends를 했으니(부모는 하나 이상을 둘 수 없기 때문에!)

Runable:
    다른Class로부터 상속받은 후, 해당Class를 Thread같이 사용가능
    Thread Class의 Method를 사용 할 수 없음 Thread를 상속한 것이 아닌, Thread를 돌리기 위한 기능들을 모아놓은 인터페이스를 implement를 했으니깐. 즉, Runnable를 구현한뒤, 추상메소드를 객관화작업이 끝이나면, Thread를 돌릴 준비가 된 상태일 뿐이다.

Runnable 클래스 생성을 했던 곳에서, 생성한 클래스를 Thread화 시키고, 실행을 해야 비로소 제 역활을 할 수 있다.




Thread를 사용하기 전에,만들 코드에서 항상 유의점이, 싱크로나이즈가 되지 않아도 되는 코드인가 여부를 아는것이 중요하다고 한다, 이유는 열심히 설명이 적혀있는것을 보면 알다싶이, 아무리 열심히 동기화를 해주고 쓰레드에 제한을 잘 잡아줘도에외현상은 생기기 마련. 임시방편책으로 쓸만한 Thread Queue를 쓴다면 그러한 문제를 어느정도 해결할 수 있으나, 듀얼코어 이상의 성능을 기대할 수 없다고 하는데 이해는 잘..

Runnable은 Interface를 상속받는 방식이기 때문에 Thread의 상속방식보다 유연하다. 상속을 하나 이상 받아야 하는상황이 자주 생길태니.


정리 잘 한 곳 http://ra2kstar.tistory.com/130

2017년 2월 20일 월요일

JAVA \r\n 문자열 \n 먹는 사태..

carriage return 이 \r
line feed 가 \n
인데 공부중에 \n은 c하면서도 잘 쓰고 해서 뭔지는 알지만, \r은 뭐고, 또 String타입 입력을 하는 도중에 엔터까지 다 씹어먹고 들어가는지 멘붕하면서 찾기시작..

자바 종특 안습 부분인듯 허다
syso를 하면 println이출력을 끝낸뒤 \r\n을 자동으로 써준다는 뜻인거 같은데,
윈도우에서 다음 라인으로 넘어가기 위한 행동이라 헌다.

유닉스에서는 \n으로 자알 돌아가는데 윈도우는 뭔가 안된다 하여 특별히 넣어준 놈인데, 이게 또 유닉스 운영체제로가면 인식을 못해서 붸에엑 한다고 한다..

초보인 나에게는 그냥 println을 주로 쓰려고 하지만, 부득이시 \n만 쓰지말고 \r\n도 쓰는 버릇을 들이면 좋을법 허다.

문자열 입력중 \n까지 씹어먹는 애로사항이 발생했다면
myScanner.nextLine(); 를 다음 문자열 입력 이전에 써보길!

JAVA 소숫점 자르기

c에서 이렇게 편하던
printf("%2f",val);
이 자바에는 비슷한 방식이 없다는것을 알고 멘붕

문논 c더쿠님들의 항의로 printf를 쓸수 있지만, 다른 방법은 뭐가 있나 해서 검색..

딱ㅎ ㅣ어느게 더 잘쓰인다 라 할건 없음

Syntax error on token "class", char expected

자바에서 class 선언시
Syntax error on token "class", char expected
이런 애러가 나타났었다
코드는 이러했다.

class object() {
    int a;
}

class object{

}
가 문법적으로 알맞는 class 생성법이었다
()를 쓰는말은 즉 method를 선언한다는건데,
이런 이유로 내가 쓴 코드는 class와 method를 같이 선언하는 꼴이 되었었다.

2017년 2월 17일 금요일

TreeMap,HashMap 값 리턴법


책에 get이 없길래 검색했는데 비유갑;


추가.
와..이걸 몰라서 검색했었다니..눈물난다..

자바 정렬 root api

정렬알고리즘에서 기준점 root 를 알아내는 키워드는 comperator, 수동 제어방법 존재
http://egloos.zum.com/iilii/v/4537561

2017년 1월 7일 토요일

JAVA basic, 생성자

생성자 in java 는 특별한 타입의 메소드이며, 객체 초기화 작업에 이용된다.
Java constructor(구조체)는 Object(객체)가 생성될때 호출되며, 값을 생성한다(It constructs the values)
i.e. provides data for the object that is why it is known as constructor.

java constructor 에서 생성규칙

생성자에서는 기본적으로 두가지 규칙이 있는데 :
  1. 생성자 이름은 반드시 클래스 이름과 동일해야하며,
  2. Return값이 존재해서는 안된다.

Java constructors의 타입

constructors에는 두가지타입이 있는데:
  1. Default(기본값) constructor (no-arg constructor 약속이(인자값이) 없는 생성자)
  2. Parameterized(매개변수화 된) constructor
java constructor



Java Default Constructor

매개변수가 없는 생산자를 default constructure 라고 한다.

default constructor형태:

1
<class_name>(){}  

Default constructor 예제

이 예제에서 우리는 no-arg(약속이 없는)생성자를 Bike 클래스에 만들었습니다. Object가 생성될때 이를 호출할 것 입니다.

1
2
3
4
5
6
    class Bike1{  
        Bike1(){System.out.println("Bike is created");}  
        public static void main(String args[]){  
          Bike1 b=new Bike1();  
        }  
    }  
Test it Now
Output:
Bike is created

Rule: 클래스에 생성자가 없는경우, 컴파일러에서 자동적으로 Default Constructor를 만듭니다.

default constructor

Q) Default constructor의 존재 이유는?

Default constructor는 Object에서 기본 값(default value)을 선언하게 되는데, 데이터타입에 따라 0 혹은 NULL값 등으로 나타압니다.

Default constructor가 선언한 기본값을 보는 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    class Student3{  
        int id;  
        String name;  
      
        void display(){
            System.out.println(id+" "+name);
        }  
      
        public static void main(String args[]){  
            Student3 s1=new Student3();  
            Student3 s2=new Student3();  
            s1.display();  
            s2.display();  
        }  
    }  
Test it Now
Output:
0 null 
0 null
 
설명:위의 클래스에서, 여러분은 어떠한 constructure를 선언하지 않았음을 눈치체실겁니다. 그런이유로, 컴파일러는 여러분에게 default construct를 선언하고, 그 값을 제공합니다. 0 과 NULL값은 default constructure에서 나온거죠.


Java parameterized(매개변수) constructor

매개변수가 있는 constructor는 parameterized constructor 라고 한다

parameterized constructor를 쓰는 이유는?

Parameterized constructor는 여러 Object들에게 여러 값들을 제공합니다.

parameterized constructor예제

이 예제에서, 우리는 Student class에 두가지 변수를 넣고, 생성자를 만들었습니다. 우리는 임의의 값을 생성자를 통해 변수에 입력할 것 입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    class Student4{  
        int id;  
        String name;  
          
        Student4(int i,String n){  
        id = i;  
        name = n;  
        }  
        void display(){
            System.out.println(id+" "+name);
        }  
       
        public static void main(String args[]){  
            Student4 s1 = new Student4(111,"Karan");  
            Student4 s2 = new Student4(222,"Aryan");  
            s1.display();  
            s2.display();  
       }  
    }  
Test it Now
Output:
111 Karan
222 Aryan
 


Constructor Overloading(오버로딩) in Java

Constructor overloading 은 JAVA에 있는 기술입니다, 한 클래스에 여러개의 생성자를 다양한 변수를 이용해 선언할 수 있습니다.컴파일러는 알아서 입력된 변수의 갯수와 타입에 따라 올바른 생성자에게 값을 보냅니다.

Constructor Overloading 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    class Student5{  
        int id;  
        String name;  
        int age;  
        Student5(int i,String n){  
            id = i;  
            name = n;  
        }  
        Student5(int i,String n,int a){  
            id = i;  
            name = n;  
            age=a;  
        }  
        void display(){
            System.out.println(id+" "+name+" "+age);
        }  
       
        public static void main(String args[]){  
            Student5 s1 = new Student5(111,"Karan");  
            Student5 s2 = new Student5(222,"Aryan",25);  
            s1.display();  
            s2.display();  
       }  
    }  
Test it Now
Output:
111 Karan 0
222 Aryan 25
 


Java에서 Constructor와 method의 차이점

constructors 와 methods 의 차이점들은 이러합니다.
Java ConstructorJava Method
Constructor는 Object를 초기화한다Method is used to expose behaviour of an object.
Constructor는 Return타입이 있어서는 안된다Method 는 반드시 Return type를 해야만한다
Constructor는 암묵적으로 호출된다.Method 는 명시적으로 호출한다.
Java compiler는 constructor를 선언하지 않을시, 자동으로
default constructor를 제공한다
Method 는 어떠한 경우에도 컴파일러가 제공하지 않는다.
Constructor 이름은 클래스이름과 동일해야만 한다Method는 클래스이름과 동일하든 안하든 상관없다


Java Copy Constructor

자바에서는 copy constructor라는것은 없지만, C++에서 copy constructor처럼 한 object의 값을 다른 object에 복사할수 있다,
한 Object의 값을 복사하는 방법은 java에서 정말 많은 방법이 있는데,
  • constructor로 부터 혹은
  • 한 Object의 값과 반대쪽을 지정하거나
  • Object클래스에서 clone() method를 이용하는 등의 방법이 있습니다.
아래 예제는, java constructor를 이용해 한 object의 값을 복사하는 코드입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    class Student6{  
        int id;  
        String name;  
        Student6(int i,String n){  
            id = i;  
            name = n;  
        }  
          
        Student6(Student6 s){  
            id = s.id;  
            name =s.name;  
        }  
        void display(){
            System.out.println(id+" "+name);
        }  
       
        public static void main(String args[]){  
            Student6 s1 = new Student6(111,"Karan");  
            Student6 s2 = new Student6(s1);  
            s1.display();  
            s2.display();  
       }  
    }  
Test it Now
Output:
111 Karan
111 Karan
 

constructor를 사용하지않고 값을 복사

우리는 한 Object의 값을 지정해서 다른 object로 복사할 수 있다. 이럴 경우에는, 새롭게 constructor를 만들 필요가 없게된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    class Student7{  
        int id;  
        String name;  
        Student7(int i,String n){  
            id = i;  
            name = n;  
        }  
        Student7(){
        }
        void display(){
            System.out.println(id+" "+name);
        }  
       
        public static void main(String args[]){  
            Student7 s1 = new Student7(111,"Karan");  
            Student7 s2 = new Student7();  
            s2.id=s1.id;  
            s2.name=s1.name;  
            s1.display();  
            s2.display();  
       }  
    }  
Test it Now
Output:
111 Karan
111 Karan
 


Q) constructor가 어떠한 값이라도 return 할 수 있나요?

A:네, 위의 예시가 그 방법의 좋은 예시입니다.(return을 쓰지는 않았지만, 값은 return했죠)

constructor가 초기화를 하는 대신, 다른 작업을 할 수 있습니까?

네, object 생성,thread 시작, method 부르기(calling method) 등 을 할수있습니다. 여러분들은 method에서 하듯이 어떠한 작업도 constructor에서 할수있습니다(You can perform any operation in the constructor as you perform in the method.)



원문보고 만든 오역쩌는 번역입니다. 영어기능자는 그냥 원문보시는게 정신건강에 이롭습니다.