2013년 5월 8일 수요일

ENUM

What is Enum in Java 
Enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java, For example Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Genericsvarargs and static import. Java Enum as type is more suitable on certain cases for example representing state of Order as NEW, PARTIAL FILL, FILL or CLOSED. Enumeration(Enum) was not originally available in Java though it was available in other language like C and C++ but eventually Java realized and introduced Enum on JDK 5 (Tiger) by keyword Enum. In this Java Enum tutorial we will see different Enum example in Java and learn using Enum in Java. Focus of this Java Enum tutorial will be on different features provided by Enum in Java and how to use them. If you have used Enumeration before in C or C++ than you will not be uncomfortable with Java Enum but in my opinion Enum in Java is more rich and versatile than in any other language. One of the common use of Enum which emerges is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safetySerialization automatically.

자바에서 Enum이란.
자바에서 Enum은 자바에서 잘 알려진 값의 고정 숫자를 대표하는데 사용하는 키워드, 기능이다. 예를 들어, 한주의 일에 대한 숫자, 태양계 시스템에서 행성의 숫자와 같은/. Enumeration(Enum)은 JDK1.5에서 소개되었고, J2SE 5에서 오토박싱/언박싱, 제네릭, varargs, static import와 더불어 나의 좋아하는 기능중에 하나이다. 타입으로서 자바 Enum은 [예를 들어, NEW, PARTIAL FILL, FILL 또는 CLOSED와 같은 순서상태를 대표하는] 특정 케이스에 좀 더 적합하다. 원래 Enum은 자바에서 사용할 수 없었다./비록 C나 C++에서는 이용가능했지만/ 그러나 점차적으로 자바는 깨달았고 JDK5에서 Enum을 소개했다. 이 자바 Enum tutorial에서 우리는 자바의 다양한 Enum 예제를 볼 것이고, 사용법을 배울 것이다. 이 자바 Enum 튜토리얼은 [Enum에 의해 제공되는 다양한 기능과 그 기능의 사용법에] 초점을 맞출 것이다. 만일 당신이 이전에 C 또는 C++에서 Enumeration을 사용한 적이 있다면 당신은 자바의 Enum에 대하여 익숙할 것이다/ 그러나 개인적으로 봤을 때 자바의 Enum은 다른 언어의 그것보다 좀 더 풍부하고 다양하다. Enum의 일반적인 사용중의 하나는 자바에서 싱글톤을 쓰는데 Enum 을 사용하는 것이다/ 그리고 그것은 여태것 싱글톤을 구현하는 가장 쉬운 방법이다/ 그리고 다루는 것이다/ 쓰레드 안전성, 시리얼라이제이션과 관련된 이슈를 자동으로 다루는/.




How to represent enumerable value without Java enum

java enum example, enum in java tutorialSince Enum in Java is only available from Java 1.5 its worth to discuss how we used to represent enumerable values in Java prior JDK 1.5 and without it. I use public static final constant to replicate enum like behavior. Let’s see an Enum example in Java to understand the concept better. In this example we will use US Currency Coin as enumerable which has values like PENNY (1) NICKLE (5), DIME (10), and QUARTER (25).

class CurrencyDenom {
            public static final int PENNY = 1;
            public static final int NICKLE = 5;
            public static final int DIME = 10;
            public static final int QUARTER = 25;

      }

class Currency {
   int currency; //CurrencyDenom.PENNY,CurrencyDenom.NICKLE,
                 // CurrencyDenom.DIME,CurrencyDenom.QUARTER
}

 Though this can serve our purpose it has some serious limitations:


가산의 값을 자바 enum 없이 표현하는 방법

자바의 Enum은 자바 1.5버전 이상에서 이용가능하기 때문에, 논의할 필요가 있다/ 우리가 가산의 값들을 자바1.5 이전 버젼에서 Enum없이 어떻게 표현하는 지를/. 나는 public static final 상수값을 사용한다/ enum을 따라하기 위해/. 자바의 Enum 예제를 살펴보자/ 개념을 더 잘 이해하기 위해/. 이 예제에서 우리는 US통화 동전을 사용할 것이다/ [PENNY(1) NICKLE(5), DIME(10), QUARTER(25)와 같은 값들을 가진] 가산으로서

CODE ...
         ..
         .
이 코드는 우리의 목적을 이루지만, 몇몇 심각한 한계를 가지고 있다.


*가산 (可算)
[명사] <수학> 자연수의 집합과 일대일의 대응을 만들 수 있음을 이르는 말. 짝수 전체의 집합, 정수 전체의 집합, 유리수 전체의 집합 따위가 지니고 있는 특성이다.

 1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to currency e.g. 99 though there is no coin to represent that value.

 2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"

3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5

Java Enum is answer of all this limitation. Enum in Java is type-safe, provides meaningful String names and has there own namespace. Now let's see same example using Enum in Java:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
  
Here Currency is our enum and PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces around enum constants because Enum are type like class and interface in Java. Also we have followed similar naming convention for enum like class and interface (first letter in Caps) and since Enum constants are implicitly static final we have used all caps to specify them like Constants in Java.


1) 타입에 안전하지 않다: 무엇보다 그것은 type-safe하지 않다.; 당신은 통화에 유효한 어떠한 int값도 할당할 수 있다. 예를 들어, 99, 비록 그 값을 나타내는 동전이 없지만.
2) 의미없는 출력: 어떤 상수값을 출력하는 것은 숫자값을 출력할 것이다/ 동전의 의미있는 이름 대신에/ 예를 들어, 당신이 NICKLE을 출력하고자 한다면, NICKLE 대신 숫자5가 출력될 것이다.
3) 이름공간의 없음.


Enum을 이용하여 String을 switch문에 사용하는 예제.
public class EnumTest {
 private enum ServiceName{
   samsung
  ,apple;
 }
 
 public static void main(String[] args) {
  printEnumTest("samsung");
 }
 
 public static void printEnumTest(String serviceName){
  switch (ServiceName.valueOf(serviceName)){
  case  samsung:
   System.out.println("samsung");
   break;
  case apple:
   System.out.println("apple");
   break;
  }
 }
}



Read more: 자바Enum

댓글 없음 :

댓글 쓰기