10 mistakes + Alpha

java core 2015. 8. 28. 15:27

Ref-Site:

 

1. 

array를 ArrayList로 전환시:

 

ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));

 

(설명)

Collection인 java.util.ArrayList 는

java.util.Arrays.ArrayList와 다름.List list = Arrays.asList(anArray)  하면  static class인

   Arrays.ArrayList가 return됨: 쓰지 말것

 

 

2. array안에 value존재하는지 check시

Arrays.asList(arr).contains(targetValue);

 

3. List에서 element하나 삭제시.

Size()가 변하는 loop안이라면 Iterator를 사용하여 삭제하는 게 안전.

아니면 뒤에서부터 앞으로 Loop돌면서 삭제. (테스트 필요)

 

Iterator<String> iter = list.iterator();
while (iter.hasNext()) {  
     String s = iter.next(); //꼭 next먼저 호출.
     if (s.equals("a"))  iter.remove()//원래 remove는 가장최근 return()한 걸 삭제하는 이상한 함수임.
}

 

ListIterator의 경우에는 iter.set() 함수도 매우 쓸만하다. //이 역시, 가장 장최근 return()한 걸 치환.

 

4. 보통은 HashMap을 쓰자.  HashTable도 동일하지만 이건 synchronized가 걸려있어 조금 늦음.

Ref-Site: top 10 Q about Map

 

5. Default 생성자는 생성자가 없을경우에만 자동으로 compiler가 넣어 줌.

   => default생성자 없는 class를 상속받을 경우 super()가 필요한데 없으므로 컴파일 에러가 남.

 

6. Sort   Ref-Site:

   => Collections.sort( list, Comparator  ),  Arrays.sort( array, Comparator  ) 사용

 

        // 역순으로 정렬하기 위한 Comparator 객체 생성
        Comparator<String> reverseComparator = new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s2.compareTo(s1);
            }
        };
        
        /**참고 */
        따라서, Comparator 클래스를 구현할 때에는 compare() 메서드를 반드시 구현해야 합니다. compareTo() 메서드는 Comparable 인터페이스에서 정의되어 있는 메서드로, 객체를 자신과 비교하여 정렬 순서를 결정하는 메서드입니다. Comparable 인터페이스를 구현하면서 compareTo() 메서드를 구현해야 하며, Comparator 클래스를 구현할 때에는 compare() 메서드를 구현해야 합니다.

 

 

 

   => Set이나 Map의 경우에는 TreeSet, TreeMap 생성 후 add하면 자동 정렬 : complexity of O(logN)

REF-Site:

 - 필요시: 생성시에 Comparator 공급.

 - Sync필요시:  SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

 

 

 

 

Posted by yongary
,

CentOS, jdk+tomcat 설치

Linux 2015. 8. 25. 13:36

 

 

1) JDK설치  Ref-Site

root로 로그인해서

#rpm -ivh jdk1.7_xx_xx.rpm  혹은

#rpm -ivh java-1.6.0-openjdk-1.6.0.0-1.45.1.11.1.el6.x86_64   (openJDK가 더 안전)

 

 

2) tomcat 설치  Ref-Site

 

오타: /lib/jsp-api.jar

Posted by yongary
,

JPA방식

Spring 2015. 8. 19. 23:35

REF-SITE 

 

Entity 어노테이션이 RDB테이블이 된다.


@Entity
public class Forum {
    @Id private Long id;
    @Column private String name;
    @Column private String description;
    @Column private Date createdAt;
 
// Omit Getters/Setters....
}


Posted by yongary
,

Frontend hacking

IT 2015. 8. 12. 23:56

SQL Injection

XSS (Cross Site Scripting) - javascirpt를 입력.  


==> 해결책: escapeHtml, escapeScirpt 등을 사용하거나, MVC framework을 사용. angular.js도 어느정도 막을 수 있을 듯.



그외,  

Command Injection

XXE(XML External Entity) 

등의 해킹법도 있음.

Posted by yongary
,

Collections

java core 2015. 8. 12. 17:53

(Sometiems ArrayList is better when no synchronize, Sometimes Vector is better because of Size doubling )

 

ArrayList : Resizable Array - fast because of index.  Add/Delete is Slow for data Copy. ==> 50% increase its array size

Vector : Similar to ArryList..  a little heavy because of synchronize processing. ==> doubles its array size

 

LinkedList: Fast for ADD/Delete.  But No Index so sequential search is slow.

 

HashSet, SortedSet,

HashMap

DelayQueue,  - - - |> BlockingQueue

Stack

 

several I/F like:

  Queue, - 보통  new LinkedList<T>();

  Deque, - 상동.    

  BlockingQueue : (waiting in some cases)

put은 queue가 꽉 차 있을 경우, take

는 queue가 비어있을 경우가 블로킹 조건이다. 

  TransferQueue

 

 

<class> 

  ConcurrentXX  Collections : thread-Safe

-ConcurrentHashMap : synchronize detail이 HashTable과 약간 다름.

   

  - SynchronousQueue: 초기 size가 0이고.. 다른Thread에서 빼려고 할때만 삽입이 가능한 놈이므로 peek도 안됨..

      

 

TreeMap -  red-black Tree 기반의 sorted NavigableMap

 

TreeSet   -  TreeMap기반.

 

PriorityQueue - Heap자료구조 기반..

PriorityQueue 클래스는 기본적으로 작은 값이 우선순위가 높은 것으로 취급합니다. 따라서, 1에서 100까지의 숫자를 PriorityQueue에 추가하면, 1이 가장 높은 우선순위를 갖게 되고, 100이 가장 낮은 우선순위를 갖게 됩니다. 따라서 poll() 메서드를 호출하면, 가장 높은 우선순위를 갖는 1이 먼저 반환됩니다.  => 체육복 코딩테스트에 사용 됨.

 

 

Posted by yongary
,

ThreadLocal은 jdk1.2부터 있었다고 하는데, 그 동안 이런게 있는지 잘 몰랐다.

 

용도는 2가지인데

1. Thread별로 싱글턴 같은 global(local)변수를 생성/관리되므로, Thread별로 분리된 변수를 사용가능.

=> REF : per-thread Singleton.

 
    ==> synchronized없이도 Lock이 자동으로 방지 될 걸로 예상 됨..(이건 좀 토론이 필요함)

 

 

1.1. 하나의 Thread안에서 여러 class가 공용메모리 처럼 사용가능. (왜냐하면 Thread안에서 global이니깐)

 

관련사이트1 , 관련사이트2

 

 

 

 File f = File.createTempFile("aaa",".tmp")  도 유사한 성격으로 동시 접근을 피할 수 있다.

 write다한 후에 보통 f.setReadOnly();

==> 똑같은 파일명으로 만들어도 알아서 숫자가 붙는 방식임. 따라서 .deleteOnExit() 설정을 꼭 해주는 게 좋다.

Posted by yongary
,

EL과 JSTL

Spring 2015. 8. 7. 14:48

참고사이트:  http://egloos.zum.com/slog2/v/3581446   https://docs.oracle.com/javaee/6/tutorial/doc/bnahq.html 

 

 

EL (expression language) -> JSP2부터 기본 지원

JSTL (JavaServer Pages Standard Tag Library ) -> c tag를 가장 많이 사용.

 

앞부분에 taglib 디렉티브로 사용함을 표시한다.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  // c:tag사용.

 

<EL>

${param.name} => request.getParameter("name");
${member} => request.getAttribute("member");

 

${member.name} => Member m = (Member)request.getAttribute("member");
m.getName();
${list["0"]} => List list = (List)request.getAttribute("list");
list.get(0);

 <JSTL>

<c:forEach items="${list}" var="listItem" >

<td>${listItem.title}</td>

</c:forEach> 

 

Posted by yongary
,

javascript관련 질문들:

 

javascript에는 function statement와 function expression이 존재한다.

비슷하지만 약간의 차이가 난다.

 

<Function>

  - function expression: var x = function fname(){}   (fname is optional) 

 => 이걸로 싱글턴 만들수 있다. class만들고 싱클턴 만드는 거 보다 less expensive.

  - function statement:   function fname(){}

 

<기타>

  - javascript 에 {blocks}  는  scope을 가지지 않는다. 

 

<슈도 파라미터 2가지>

  - arguments : parameter와 밀접한 관계가 있으므로, read-only로 사용하는 게 좋다.

       일종의 array로 최근(ES5)에 .reduce 등이 소개되었다. 
         arguments.length

         arguments[i]

 

  - this : function 내에서 멤버변수를위한 public 키워드처럼 동작하기도 하며, (이건 아래2번)

1. reference to the object of invocation

2. allows to know the concerned Object

3. allows single function object to service many functions ?

4. key to prototype inheritance

 

Function.prototype.bind를 통해 this를 강제로 할당 할 수 있다.

 


<prototype이란>

All JavaScript objects inherit the properties and methods from their prototype.

Allows you to add properties and methods to an object 

we can inherit using prototype. and by overriding construct(). => prototype is copied.




<function관련 Form종류들>

  - New폼:      new functionObject() 

  - function폼: functionObject(arg) 이 경우, var that = this; 많이 사용. inner function이 outer를 접근하기 위해서..
                     (왜냐면 자체 this가 있기 때문)

  - method폼:  functionObject(arg).method()

  - apply폼:    apply()  form  ,   유사한것으로 call도 있는데, apply는 (this,array)  call은 (this, a,b,c : each object of array)가 전달된다.

 

 

this 참고사이트:  http://mobicon.tistory.com/189  

유투브:   15분-this,  30분-closure  (English)








Posted by yongary
,

hoisting, strict mode

javascript 2015. 8. 4. 19:19

javascript에서 hoisting이란 

 변수나 함수를 var 로 선언하기 전에도 사용할 수 있다는 의미이다.  참고사이트

(global함수의 경우는 어디서나 사용할 수 있으므로 hoisting이 아니다.)


참고사이트:영어

In JavaScript,  a variable can be used before it has been declared.


hoisting이 왜 중요한가?

==> 크드가 잘 돌아가더라도 hoisting이 동작한 것일 수 있기 때문에, hoisting을 알아두는 것이 각종버그를 방지할 수 있다.


strict mode : "use strict";  를 사용하면  hoisting을 방지할 수 있다. (꼭 선언 후 사용하는 모드)  w3schools_js



Posted by yongary
,

some JAVA keywords

java core 2015. 8. 2. 22:49

finalize(): GC calls when Instance is garbage collected. which has no reference.    참고사이트:


hashCode();  when making equals method of Object. we must consider this method().


final: (method or class) will not be inheritted.





Posted by yongary
,