from http://www.java2s.com/Tutorial/Java/0040__Data-Type/Switchstatementwithenum.htm


enum 대상을 switch 할때 요상한 각종 변환을 하는 삽질할 수 있다. 어케든 될순 있을지 몰라도 사실 그냥 enum 그대로 쓰면된다. 간단하다.

switch 대상으로 enum 이 오면 끝난다.


그리고 case 각각은 enum 의 원소가 되면된다.


ex

public class MainClass {
  enum Choice { Choice1, Choice2, Choice3 }
  public static void main(String[] args) {
    Choice ch = Choice.Choice1;

    switch(ch) {
      case Choice1:
        System.out.println("Choice1 selected");
        break;
     case Choice2:
       System.out.println("Choice2 selected");
       break;
     case Choice3:
       System.out.println("Choice3 selected");
       break;
    }
  }
}


쉽게이해하도록 그림으로 그려봤다.
이론상 틀린 그림형태이거나 구조일순있으나 컨셉자체를 잡고 가는데 도움이 될것이다.

이 모든건 자바가 call by value 이기 때문이다.

package com.javaTest.Ref;

import java.util.HashMap;
import java.util.Map;

/**
* Created by macbookpro on 2016. 12. 12..
*/
public class Ref001 {

public static void main(String[] args) {
Ref001 main = new Ref001();
main.ref001();
}

public void ref001() {
int a= 1;
Map map = new HashMap<>();

Map entireMap = new HashMap();

entireMap.put("map",map);
entireMap.put("a",a);

if(entireMap.get("map") == map) {
System.out.println("== same...");
}
if(entireMap.get("map").equals(map)) {
System.out.println("equals same...");
}

doTest(entireMap);
System.out.println("changed::"+entireMap.toString());

doTest2(entireMap);
System.out.println("no changed 2::"+entireMap.toString());

doTest3(entireMap);
System.out.println("no changed 3::"+entireMap.toString());
}

private void doTest(Map entireMap) {
System.out.println(entireMap.toString());
entireMap.put("a",2); // 이 값은 바뀜
Map m = (Map) entireMap.get("map");
m.put("change","Y");

}

private void doTest2(Map entireMap) {
// 이건 지워지지 않는다. 왜냐면 자바는 COV 이다 copy of value. 해서 지워지지 못한다
// 다만 primitive 타입이 아니면 참조복사가 되어 수정된다 해서 doTest 는 수정된것이다.
entireMap = new HashMap();

}

private void doTest3(Map entireMap) {
// cpv 이다 해당 레퍼런스에 직접 뭔가 하지 않는이상 모든 행위는(각종 재선언. 즉 new 나 다른 레퍼런스 대입) 복제된곳에 하는거다.
Map newMap = new HashMap();

entireMap = newMap;

}

}


결과

== same...
equals same...
{a=1, map={}}
changed::{a=2, map={change=Y}}
no changed 2::{a=2, map={change=Y}}
no changed 3::{a=2, map={change=Y}} 




2017-05-26 

자바스크립트에서는

$.isNumeric or isNaN or 정규식 정도가 있습니다.



previous... 이하 


from http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java


NumberUtils.isNumber or StringUtils.isNumeric from Apache Commons Lang.

You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. (The linked javadocs contain detailed examples for each method.)

shareimprove this answer



from  http://codereview.stackexchange.com/questions/57078/more-elegant-way-to-increment-integers-in-map



map.merge(arr[11],1,(existValue,initValue) -> existValue+initValue);


위의 의미는 map 안에 arr[11] 의 키로 값이 없으면 1(initValue) 을 설정하고, 있으면 교체하기를 BiFunction 함수로 정의된대로 교체된다.

함수를 보면 existValue( 즉 arr[11] 에 있던 값) + initValue(arr[11] 다음에 정의된 값인 1 이다) 로 된다.

결과 처음에는 1 일테고, 다음에 또 해당 키로 put 이 들어오면 2가 되고(1+1이니까) 그 다음은 2+1 == 3 이 되고... 이런식이다. 



occurrences.compute(token, (tokenKey, oldValue) -> oldValue == null ? 1 : oldValue + 1);



아래는 javadoc


  • compute

    public V compute(K key,
                     BiFunction<? super K,? super V,? extends V> remappingFunction)
    Description copied from interface: Map
    Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). For example, to either create or append a String msg to a value mapping:
     
     map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))
    (Method merge() is often simpler to use for such purposes.)

    If the function returns null, the mapping is removed (or remains absent if initially absent). If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.

    Specified by:
    compute in interface Map<K,V>
    Parameters:
    key - key with which the specified value is to be associated
    remappingFunction - the function to compute a value
    Returns:
    the new value associated with the specified key, or null if none

  • merge

    public V merge(K key,
                   V value,
                   BiFunction<? super V,? super V,? extends V> remappingFunction)
    Description copied from interface: Map
    If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key. For example, to either create or append a String msg to a value mapping:
     
     map.merge(key, msg, String::concat)
     

    If the function returns null the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.

    Specified by:
    merge in interface Map<K,V>
    Parameters:
    key - key with which the resulting value is to be associated
    value - the non-null value to be merged with the existing value associated with the key or, if no existing value or a null value is associated with the key, to be associated with the key
    remappingFunction - the function to recompute a value if present
    Returns:
    the new value associated with the specified key, or null if no value is associated with the key




jackson 라이브러리쪽에보면 있다. ObjectMapper 의 readValue 메서드를 통해서 할 수 있다. 


map -> json 은

Map map = new HashMap();
map.put("1","a");
map.put("2","a");
map.put("3","a");

String json = null;

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new AfterburnerModule());
try {
json = objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
e.printStackTrace();
}

간단한 예제인다. 참고바란다. 



2017-09-18 번역서에 있는글이 있어서 올린다.

표현식과 문장 모두 프로그램에서 작성하는 명령어들이며, 컴퓨터로 하여금 특정 일을 수행하도록 명령한다.

차이점은 

문장은 액션을 수행하지만 아무것도 리턴하지 않고

표현식은 액션을 수행하고 결과를 리턴한다. 람다 표현식을 사용하여 프로그래밍할 때 문장보다는 표현식을 생성하여 사용하는것이 낫다.

이유?

1. 문장은 아무것도 리턴하지 않기 때문에 사이드 이펙트를 발생하거나 메모리를 이상한값으로 채울 수 있다.

2. 문장과는 달리 표현식은 두개이상의 표현식을 하나로 조합하여 사용할 수 있음.



from http://lambda-the-ultimate.org/node/1044

Expressions have a value, while statements do not. If you can pass it as an argument to a function, it's an expression. If you can't, it's a statement. Control flow constructs in C-derived languages are generally statements (you can't pass an 'if {}' block as a function parameter). Consequently, those languages tend to provide an expression form for 'if' (like the ternary operator). Of course, the whole point of many functional languages is that everything has a value, and that functions are first-class values, which means that everything is an expression. Statements usually appear in imperative languages, where you wish to write commands that don't necessarily return a value.

구문이 값을 가지지 않을때 표현식은 값을 가진다. 만약 함수에게 아규먼트로 넘겨줄수 있다면 그건 표현식이다. 못한다면? 그건 구문이다. 제어흐름 기반의 C 파생언어들은 보통 구문( 함수파라미터 같은 'if {}' 블럭은 넘기지 못한다.) 이다. 따라서 저러한 언어들은 'if' (삼항연산같은 )를 위해 표현식 폼을 제공하는 경향이 있습니다. 물론 많은 함수언어의 중요 포인트는 모든것은 값을 가지고 함수는 일급함수 값(즉 모든것은 표현식이다)이라는 것이다. 구문은 보통 리턴값이 필요 없는 명령어를 코딩하는 명령형 언어에서 나타난다.


구문( 'if {}' ..조건이 아닌 전체 인..블럭은 함수의 아규먼트로 못넘김) 

함수파라미터처럼 if{} 블럭은 넘기지 못한다 == 구문 


from http://python.xwmooc.org/html/book004.html

3.6  표현식(Expression)

표현식 (expression)은 값, 변수, 연산자 조합니다. 값은 자체로 표현식이고, 변수도 동일하다. 따라서 다음 표현식은 모두 적합하다. (변수 x는 사전에 어떤 값이 대입되었다고 가정한다.)

17
x
x + 17



3.4  문장(Statement)

문장(statement)은 파이썬 인터프리터가 실행하는 코드 단위다. 지금까지 print, assignment 두 종류의 문장을 살펴봤습니다.

print 1
x = 2
print x



Expressions(표현식) 은 이 있고 statements(구문) 은 그렇지 않다. 

function 에게 arguments로 넘겨줄수 있는것이라면 그건 표현식이다. 그럴수 없다면? 구문이다. 

구문도 표현식처럼 값을 줄 수 있는데 그게바로 return문을 이용할때이다!


이게 가장 쉬운 설명인것 같다.

구문은 if {} 이런게 구문이다. 이건 값으로 넘겨줄 수 있는.. 어떤 값이 아니다. 


Statements are commands, expressions are requests

Statements are commands, i.e. 'do this', 'open file', 'set collection size to 1', 'clear collection' etc.

Expressions are requests: 'calculate this', 'give me the contents of this file', 'give me a collection with size 1', 'give me a new collection'.

Superficially, they are both commands, in the sense that expressions are commands to perform calculations. But the real difference lies inside statements and expressions:

-In statements, the programmer tells the computer where to store the results of computations.
: 구문은 프로그래머가 컴퓨터에게 계산의 결과를 어디에 저장할지 말하는것이고...

-In expressions, the programmer does not tell the computer where to store the result of computations, but takes the result in his/her hand, and passes it to other expressions.
: 표현식은 프로그래머가 컴퓨터에게 계산의 결과를 어디에 저장할지 말하지 않는것이다. 그러나 그 결과는 다른 표현식에 전달된다.

The problem created by statements is that the programmer often forgets the right place to store the result of computations, and therefore uses a wrong place, thus creating havoc with a program; whereas in expressions the store does not matter, because the result is to be immediately used in a nearby expression.

It's a very subtle difference, but once someone understands it, he/she automatically understands the real value of functional programming.



'IT > java' 카테고리의 다른 글

map 의 .merge ( java 8 lambda) 값 증가 를 간단히  (0) 2016.09.06
json <-> map  (0) 2016.08.17
java 8 tutorial 한글  (2) 2014.04.09
잘못쓰면 큰일나는 loop 과 객체선언 ... 그리고 성능저하  (0) 2013.09.26
call by ref ? value?  (0) 2013.06.21


아래의 글은 아직 작업중이라서 오역 및 오류가 가득할 수 있음을 알려드립니다.

github 쪽으로 markdown 작업중이니 해당 페이지에 가서 오류정정등을 하시면됩니다. (라지만 해당 github 에서 뭔가 협업을 해본적이 없어서 제대로 처리할지 0.0001% 걱정입니다)


최신버전은 https://github.com/yakmoz/ref/blob/master/java/java%208%20tutorial.md 를 통해서 확인해주세요 



Java 8 Tutorial (KOREAN)

... 아무래도 수정이 힘들어 github 쪽의 파일로 참고 부탁드립니다. 





사실 아주 사소한 부분에서 부터 생각보다 큰 문제가 발생하곤 한다.


이번이 그랬다...


현재 일하고 있는 사이트에서 특정 대상수가 아주 많아지면(수백개이상) 성능이 느려지는 문제가 있었다.

사람들은 처음에 쿼리를 의심했다 (나오는 exception 이 그러했거든... 그부분은 우선 넘어가고)


허나 점점 이건 쿼리 문제가 아니라는 느낌이 들었고 결과를 보면 맞는듯 했다.


이중루프가 과도하게 돌 수 있는 케이스가 존재하고 있었다. 

해서 그 내부루프를 map 으로 변경해서 어마어마? 한 성능향상을 이루었다.


그러나 반전이 있었으니...


아무래도 루프가 그정도 돈다고 (물론 많이 돌긴한다; 수십만회?) 그렇게 느려질수 있는가는 의문이랄까?

그리고 찾아보니 그와 유사한 혹은 더 많은 루프를 도는 케이스도 나왔는데 그건 ms 안에 종료되었다.


어.. 이상하다 역시... 이게 아니었어;



결과는... 두둥


Map 의 선언이 루프에 있었다는것이다.


즉 500개의 아이템이 있다면 500번만 생성되면된다.

그게 중첩루프를 돌더라도 말이다. (특정조건일때만 new 해서 맵을 생성함)


그런데 ... 어찌된건지; 맵의 선언을 조건절 밖에 두었고 결과


500*500 번의 인스턴스가 생성된것이다.

원래는 500개만 생성할것을;



어이없는 실수였지만 (당연히 평소에 저런식으로 생성하지 않는다; )


찾을때는 생각보다 시간이 오래 걸렸다; 



loop 을 돌면서 뭔가 리스트에 맵을 넣어야 할 경우, 나처럼 잘못된 인스턴스 생성으로 아이템수가 적을때는 몰랐다가 많아지면 생길 수 있는 성능이슈에 대해서 조심하도록 하자;  한마디로 항상 루핑조건을 만들땐 조심하자; 



+ Recent posts