함수와 메소드의 차이

Posted by epicdev Archive : 2013. 4. 18. 00:02

여태껏 함수와 메소드, 변수와 필드등의 용어들을 혼재해서 막 써왔었는데 이번 기회에 확실하게 기억해 놓아야 겠습니다.

아래의 표를 보시면 각 객체지향언어에서 멤버 변수와 멤버 함수들을 어떻게 지칭하는지 알 수 있습니다.


출처: http://blog.naver.com/cdincdin?Redirect=Log&logNo=30129625682



  

출처: http://stackoverflow.com/questions/8100376/class-forname-vs-classloader-loadclass-which-to-use-for-dynamic-loading


Class.forName()의 경우 이 메소드를 호출한 클래스의 class loader를 사용한다. 그리고 생성되는 클래스의 전역 초기화 코드가 실행된다.


ClassLoader.loadClass()의 경우 주어진 class loader를 사용하며, 생성되는 클래스의 전역 초기화 코드가 실행되지 않는다.

  

Effective Java 목차

Posted by epicdev Archive : 2013. 4. 3. 01:35

이 항목들을 가끔씩 보면서 각각의 아이템들이 어떤 것을 의미했었는지 되새겨 보는 것도 좋을 것 같습니다.


1. Creating and Destroying Objects

Item 1: Consider static factory methods instead of constructors

Item 2: Consider a builder when faced with many constructor parameters

Item 3: Enforce the singleton property with a private constructor or an enum type

Item 4: Enforce noninstantiability with a private constructor

Item 5: Avoid creating unnecessary objects

Item 6: Eliminate obsolete object references

Item 7: Avoid finalizers


2. Methods Common to All Objects

Item 8: Obey the general contract when overriding equals

Item 9: Always override hashCode when you override equals

Item 10: Always override toString

Item 11: Override clone judiciously

Item 12: Consider implementing Comparable


3. Classes and Interfaces

Item 13: Minimize the accessibility of classes and members

Item 14: In public classes, use accessor methods, not public fields

Item 15: Minimize mutability

Item 16: Favor composition over inheritance

Item 17: Design and document for inheritance or else prohibit it

Item 18: Prefer interfaces to abstract classes

Item 19: Use interfaces only to define types

Item 20: Prefer class hierarchies to tagged classes

Item 21: Use function objects to represent strategies

Item 22: Favor static member classes over nonstatic


4. Generics

Item 23: Don't use raw types in new code

Item 24: Eliminate unchecked warnings

Item 25: Prefer lists to arrays

Item 26: Favor generic types

Item 27: Favor generic methods

Item 28: Use bounded wildcards to increase API flexibility

Item 29: Consider typesafe heterogeneous containers


5. Enums and Annotations

Item 30: Use enums instead of int constants

Item 31: Use instance fields instead of ordinals

Item 32: Use EnumSet instead of bit fields

Item 33: Use EnumMap instead of ordinal indexing

Item 34: Emulate extensible enums with interfaces

Item 35: Prefer annotations to naming patterns

Item 36: Consistently use the Override annotation

Item 37: Use marker interfaces to define types


6. Methods

Item 38: Check parameters for validity

Item 39: Make defensive copies when needed

Item 40: Design method signatures carefully

Item 41: Use overloading judiciously

Item 42: Use varargs judiciously

Item 43: Return empty arrays or collections, not nulls

Item 44: Write doc comments for all exposed API elements


7. General Programming

Item 45: Minimize the scope of local variables

Item 46: Prefer for-each loops to traditional for loops

Item 47: Know and use the libraries

Item 48: Avoid float and double if exact answers are required

Item 49: Prefer primitive types to boxed primitives

Item 50: Avoid strings where other types are more appropriate

Item 51: Beware the performance of string concatenation

Item 52: Refer to objects by their interfaces

Item 53: Prefer interfaces to reflection

Item 54: Use native methods judiciously

Item 55: Optimize judiciously

Item 56: Adhere to generally accepted naming conventions


8. Exceptions

Item 57: Use exceptions only for exceptional conditions

Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors

Item 59: Avoid unnecessary use of checked exceptions

Item 60: Favor the use of standard exceptions

Item 61: Throw exceptions appropriate to the abstraction

Item 62: Document all exceptions thrown by each method

Item 63: Include failure-capture information in detail messages

Item 64: Strive for failure atomicity

Item 65: Don't ignore exceptions


9. Concurrency

Item 66: Synchronize access to shared mutable data

Item 67: Avoid excessive synchronization

Item 68: Prefer executors and tasks to threads

Item 69: Prefer concurrency utilities to wait and notify

Item 70: Document thread safety

Item 71: Use lazy initialization judiciously

Item 72: Don't depend on the thread scheduler

Item 73: Avoid thread groups


10. Serialization

Item 74: Implement Serializable judiciously

Item 75: Consider using a custom serialized form

Item 76: Write readObject methods defensively

Item 77: For instance control, prefer enum types to readResolve

Item 78: Consider serialization proxies instead of serialized instances




Effective Java, 2/E(Paperback)

저자
Block, Joshua 지음
출판사
Addison-Wesley | 2008-06-09 출간
카테고리
과학/기술
책소개
Designed to help Java programmers m...
가격비교



[업데이트 2013.04.03]


한글 목차도 올려봅니다


1. 객체의 생성과 소멸

[항목 1] 생성자 대신 static 팩토리(factory) 메소드 사용을 고려하자

[항목 2] 생성자의 매개변수가 많을 때는 빌더(builder)를 고려하자

[항목 3] private 생성자나 enum 타입을 사용해서 싱글톤의 특성을 유지하자

[항목 4] private 생성자를 사용해서 인스턴스 생성을 못하게 하자

[항목 5] 불필요한 객체의 생성을 피하자

[항목 6] 쓸모 없는 객체 참조를 제거하자

[항목 7] 파이널라이저(finalizer)의 사용을 피하자


2. 모든 객체에 공통적인 메소드

[항목 8] equals 메소드를 오버라이딩 할 때는 보편적 계약을 따르자

[항목 9] equals 메소드를 오버라이드 할 때는 hashCode 메소드도 항상 같이 오버라이드 하자

[항목 10] toString 메소드는 항상 오버라이드 하자

[항목 11] clone 메소드는 신중하게 오버라이드 하자

[항목 12] Comparable 인터페이스의 구현을 고려하자


3. 클래스와 인터페이스

[항목 13] 클래스와 그 멤버의 접근성을 최소화하자

[항목 14] public 클래스에서는 public 필드가 아닌 접근자(accessor) 메소드를 사용한다

[항목 15] 가변성을 최소화 하자

[항목 16] 가급적 상속(inheritance)보다는 컴포지션(composition)을 사용하자

[항목 17] 상속을 위한 설계와 문서화를 하자. 그렇지 않다면 상속의 사용을 금지시킨다

[항목 18] 추상 클래스보다는 인터페이스를 사용하자

[항목 19] 타입을 정의할 때만 인터페이스를 사용하자

[항목 20] 태그(tagged) 클래스보다는 클래스 계층을 사용하자

[항목 21] 전략을 표현할 때 함수 객체를 사용하자

[항목 22] static 멤버 클래스를 많이 사용하자


4. 제네릭(Generics)

[항목 23] 새로 작성하는 코드에서는 원천(raw) 타입을 사용하지 말자

[항목 24] 컴파일 경고 메시지가 없게 하자

[항목 25] 배열보다는 List를 사용하자

[항목 26] 제네릭 타입을 애용하자

[항목 27] 제네릭 메소드를 애용하자

[항목 28] 바운드 와일드 카드를 사용해서 API의 유연성을 높이자

[항목 29] 타입 안전이 보장되는 혼성(heterogeneous) 컨테이너의 사용을 고려하자


5. 열거형(Enum)과 주석(Annotation)

[항목 30] int 상수 대신 enum을 사용하자

[항목 31] 서수(序數) 대신 인스턴스 필드를 사용하자

[항목 32] 비트(bit) 필드 대신 EnumSet을 사용하자

[항목 33] 서수(序數) 인덱스 대신 EnumMap을 사용하자

[항목 34] 인터페이스를 사용해서 확장 가능한 enum을 만들자

[항목 35] 작명 패턴보다는 주석(annotation)을 사용하자

[항목 36] Override 주석을 일관성 있게 사용하자

[항목 37] 타입 정의는 표시 인터페이스를 사용하자


6. 메소드(method)

[항목 38] 매개 변수가 유효한지 검사하자

[항목 39] 필요하면 방어 복사본을 만들자

[항목 40] 메소드 시그니처를 신중하게 설계하자

[항목 41] 오버로딩(overloading)을 분별력 있게 사용하자

[항목 42] 가변 인자(varargs)를 분별력 있게 사용하자

[항목 43] null대신 비어있는 배열이나 컬렉션을 반환하자

[항목 44] 외부에 제공하는 모든 API 요소에 대해 문서화 주석을 넣자


7. 프로그래밍 일반

[항목 45] 지역 변수의 유효 범위를 최소화 하자

[항목 46] 종전의 for 루프보다는 for-each 루프를 사용하자

[항목 47] 라이브러리를 배우고 사용하자

[항목 48] 정확한 계산에는 float나 double 타입을 쓰지 말자

[항목 49] 박스화 기본형보다는 기본형을 사용하자

[항목 50] 다른 타입을 쓸 수 있는 곳에서는 String 사용을 피하자

[항목 51] 문자열 결합의 성능 저하를 주의하자

[항목 52] 객체 참조는 그 객체의 인터페이스 타입으로 하자

[항목 53] 리플렉션보다는 인터페이스를 사용하자

[항목 54] 네이티브 메소드를 분별력 있게 사용하자

[항목 55] 잘 판단해서 최적화하자

[항목 56] 보편화된 작명 규칙을 따르자


8. 예외(Exceptions)

[항목 57] 예외 상황에서만 예외를 사용하자

[항목 58] 복구 가능 상황에는 checked 예외를 사용하고 런타임 예외는 프로그램 에러에 사용하자

[항목 59] checked 예외의 불필요한 사용을 피하자

[항목 60] 표준 예외를 사용하자

[항목 61] 하위 계층의 예외 처리를 신중하게 하자

[항목 62] 메소드가 던지는 모든 예외를 문서화하자

[항목 63] 실패 상황 정보를 상세 메시지에 포함하자

[항목 64] 실패 원자성을 갖도록 노력하자

[항목 65] 예외를 묵살하지 말자


9. 동시성(Concurrency)

[항목 66] 공유하는 가변 데이터에 접근 시 동기화하자

[항목 67] 지나친 동기화는 피하자

[항목 68] 스레드 그룹보다는 실행자와 작업을 사용하자

[항목 69] wait와 notify 대신 동시성 유틸리티를 사용하자

[항목 70] 스레드 안전을 문서화 하자

[항목 71] 늦 초기화를 분별력 있게 사용하자

[항목 72] 스레드 스케줄러에 의존하지 말자

[항목 73] 스레드 그룹을 사용하지 말자


10. 직렬화(Serialization)

[항목 74] Serializable 인터페이스를 분별력 있게 구현하자

[항목 75] 독자적인 직렬화 형태의 사용을 고려하자

[항목 76] 방어 가능한 readObject 메소드를 작성하자

[항목 77] 인스턴스 제어에는 readResolve 메소드보다 enum 타입을 사용하자

[항목 78] 직렬화된 인스턴스 대신 직렬화 프록시의 사용을 고려하자




이펙티브 자바(EFFECTIVE JAVA)(제2판)

저자
JOSHUA BLOCH 지음
출판사
대웅 | 2009-04-13 출간
카테고리
컴퓨터/IT
책소개
더 명쾌하고, 더 정확하고, 더 강력하고, 재사용 가능한 코드를...
가격비교


  

Java Generics에서 발생하는 Type Erasure

Posted by epicdev Archive : 2013. 3. 25. 10:31

Java Generics에서 발생하는 Type Erasure에 대해서 잘 설명하고 있는 글


http://javapapers.com/core-java/type-erasure/

  

Word Cloud 생성기

Posted by epicdev Archive : 2012. 9. 8. 19:52

Wordle(http://www.wordle.net/)이 한글을 지원하지 않기 때문에, 한글 Word Cloud를 생성하기 위해서 재미삼아 만들어 보았습니다.

GitHub: https://github.com/epicdevs/Word-Cloud


몇시간만에 만든거라서 퀄리티는 그렇게 좋지 않지만, Word Cloud가 어떤식으로 만들어지는지는 파악할 수 있습니다.

Wordle혹은 일반적인 Word cloud를 생성하는 자세한 알고리즘을 알고 싶으시면

아래의 문서와 페이지를 참조하시길 바랍니다

http://static.mrfeinberg.com/bv_ch03.pdf

http://mathematica.stackexchange.com/questions/2334/how-to-create-word-clouds/2360#2360






  

Java에서 사용되는 System.out의 경우 default는 console로 지정이 되어있습니다.

System.out은 System클래스의 static instance로써 PrintStream object 입니다.

따라서 이 System.out을 다른 PrintStream으로 바꿔준다면, System.out을 console이 다른 곳에 출력하도록 할 수 있을 것입니다.

만약 System.out을 잔뜩 사용해서 화면에 log를 출력하던 프로그램이 있는데

화면에 출력하는 방식이 아닌 파일로 출력하는 방식으로 바꾸어야 한다면

기존에 사용했던 System.out을 하나하나 파일로 쓰는 코드로 변환할 필요없이

System.out 자체를 다른 PrintStream으로 간단하게 변경하여

기존의 모든 코드를 수정하는 번거로움을 피할 수 있습니다.



위의 코드에서는

System.out은 console로 두고 System.err은 로그파일로 두어서

기본적인 내용은 화면에 출력하고, 중요한 에러들은 로그파일에 출력하도록 한 것입니다.

  

Java의 HashMap에서 key값으로 primitive type은 올 수 없다.

그래서 int가 key값으로 필요하다면 Integer를 대신 사용하게 된다.


그런데 여기에서 짚고 넘어가야 할 점이 하나 있다.

HashMap에서는 key의 hashCode()값을 기준으로 entry를 찾기 때문에

처음 HashMap에 entry를 넣을 때의 key의 hashCode()값과

entry를 불러 올 때의 key의 hashCode()값이 같아야 한다.

그래서 HashMap에 entry를 넣을 때의 Integer의 reference를 유지해야,

나중에 HashMap에서 entry를 불러 올 때 사용할 수 있다라고 생각하기 쉽다.



위의 경우 과연 Integer value는 null일까?

단순히 생각해 봤을때 처음 entry를 넣을 때 Integer 객체를 하나 생성했고

entry를 찾을 때 새로운 Integer 객체를 생성했기 때문에 null값이 나올 것이라고 생각할 수도 있다.

하지만 실제로 해보면 null값이 아니라 30을 값으로 지니는 Integer가 반환된다.


그렇다면 왜 그런 것일까?

이는 Java API의 Integer의 hashCode() 부분을 보면 쉽게 알 수 있다.


hashCode

public int hashCode()
Returns a hash code for this Integer.

Overrides:
hashCode in class Object
Returns:
a hash code value for this object, equal to the primitive int value represented by this Integer object.


즉, Integer의 hashCode()를 호출하면 Integer가 표현하고 있는 primitive int 값을 리턴한다.

Integer를 언제 어디서 얼마나 많이 생성하던지간에, Integer가 표현하는 primitive int값이 같다면 모두 같은 instance를 공유하는것이 된다.

따라서 HashMap에서 Integer를 사용할 때 쓸데없이 많은 생각을 하지 않아도 된다.



위와 같은 HashMap의 사용이 가능한 것도 모두 같은 원리로써 설명이 가능하다.

  

Java transient 키워드에 대해 몰랐던 사실

Posted by epicdev Archive : 2012. 8. 26. 19:10

Java에는 transient라는 키워드가 존재합니다. 예를 들어 아래처럼 클래스의 멤버변수를 선언할 때 붙일 수 있는 키워드입니다.



일반적으로 transient 키워드는 단순히 Java에서 serialization을 할 때, 특정 멤버변수가 serialization이 되는 것을 막는 것이라고 알려져 있습니다.

물론 맞는 말이구요. 그런데 곰곰이 생각해 보면 이게 정말 하나의 프로그래밍 언어에서 키워드로 지정해야할 수준의 중요성을 지니고 있는 것인가? 라는 의문이 들었습니다.


그래서 좀 찾아봤더니 실제로 그런 의견들이 있었습니다.


출처: http://stackoverflow.com/questions/910374/why-does-java-have-transient-variables


Serialization systems other than the native java one can also use this modifier. Hibernate, for instance, will not persist fields marked with either @Transient or the transient modifier. Terracotta as well respects this modifier.

I believe the figurative meaning of the modifier is "this field is for in-memory use only. don't persist or move it outside of this particular VM in any way. Its non-portable". i.e. you can't rely on its value in another VM memory space. Much like volatile means you can't rely on certain memory and thread semantics.


그리고 댓글에는


I think that transient wouldn't be a keyword if it were designed at this time. They'd probably use an annotation


요약을 해보면 이 transient라는 것은 옛날에 Java가 만들어 질 때 만들어 진 키워드입니다.

만약 이러한 기능이 지금에 와서 만들어 졌다면, transient같은 키워드가 아닌 Java 5부터 소개된 Annotation(@)을 활용해서 이러한 것들이 정의되도록 설계를 했을 것입니다. 이것은 volatile같은 키워드에도 똑같이 적용될 수 있습니다.


실제로 이러한 transient나 volatile같은 키워드들은 VM마다 다르게 구현이 되어있기 때문에, JVM이 아닌 다른 VM을 쓸 경우 제대로 동작하지 않을 수도 있다고 합니다.

그래서 결론은, transient를 그냥 단순히 serialization을 방지하는 키워드라고 외우는 것보다는, transient라는 키워드의 본질적인 의미인, 이 멤버 변수는 "메모리 안에서만 사용되어야한다"라는 것을 암시하는 키워드라고 알아두어야 할 것입니다. 그래서 이러한 키워드의 의미를 JVM에서는 serialization이 되지 않도록 구현을 한 것입니다. 다른 VM에서는 어떻게 구현을 하던간에 transient의 본질적인 의미만 어기지 않으면 되는 것입니다.

  

HashSet vs TreeSet

Posted by epicdev Archive : 2012. 8. 23. 20:01

출처: http://stackoverflow.com/questions/1463284/hashset-vs-treeset


HashSet is much faster than TreeSet (constant-time versus log-time for most operations like add, remove and contains) but offers no ordering guarantees like TreeSet.

HashSet:

  • class offers constant time performance for the basic operations (add, remove, contains and size).
  • it does not guarantee that the order of elements will remain constant over time
  • iteration performance depends on the initial capacity and the load factor of the HashSet.
    • It's quite safe to accept default load factor but you may want to specify an initial capacity that's about twice the size to which you expect the set to grow.

TreeSet:

  • guarantees log(n) time cost for the basic operations (add, remove and contains)
  • guarantees that elements of set will be sorted (ascending, natural, or the one specified by you via it's constructor)
  • doesn't offer any tuning parameters for iteration performance
  • offers a few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc

Important points:

  • Both guarantee duplicate-free collection of elements
  • It is generally faster to add elements to the HashSet and then convert the collection to a TreeSet for a duplicate-free sorted traversal.
  • None of these implementation are synchronized. That is if multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.
  • LinkedHashSet is in some sense intermediate between HashSet and TreeSet. Implemented as a hash table with a linked list running through it, however it provides insertion-ordered iteration which is not same as sorted traversal guaranteed by TreeSet.

So choice of usage depends entirely on your needs but I feel that even if you need an ordered collection then you should still prefer HashSet to create the Set and then convert it into TreeSet.

  • e.g. Set<String> s = new TreeSet<String>(hashSet);

  

HashTable vs HashMap vs ConcurrentHashMap

Posted by epicdev Archive : 2012. 8. 23. 19:41

출처: http://apurvagnihotri.blogspot.kr/2010/06/hashmap-vs-hashtable.html


HashMap and HashTable both provide key-value access to data.


The Hashtable is among the original collection classes in Java.Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface. HashMap is part of the new Collections Framework, added with Java 2.


The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap is not synchronized.This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones


HashMap has a more complex hashing algorithm then Hashtable. It takes the hash value from the key and then hashes it again (double hashing). This can improve the distribution of the keys and hence the performance of the Map.


Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If we change the map while iterating, it will throw exception. 


Third difference is that HashMap permits null values in it, while Hashtable doesn't.Also note that only one NULL value is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.


Using ConcurrentHashmap: for having a thread safe map we can use ConcurrenthashMap(from java5 onwards) as well instead of Hashtable which has become obsolete.


private Map myConcMap = new ConcurrentHashMap();


Now The question arises why ConcurrentHashMap and not HashTable or just have a synchronised access to HasMap.


So the major advantage of using ConcurrentHashMap is "performance" as the lock is not applied on wholeMap as is the case with a Synchronised access to hashmap or Hashtable.


As we know that hash maps store their data in a series of separate buckets, it is possible to lock only the portion of the map that is being accessed.ConcurrentHashMap uses this to provide us a highly optimized synchronised way of accessing HashMap.ConcurrentHash hash map follows following to provide a concurrent access:


1. Writing to a ConcurrentHashMap locks only a portion of the map

2. Reads can occur without locking.


Some disadvantges of ConcurrentHashMap:

ConcurrentHashMap will generally take up more memory.

it cannot take null as a key.

  
 «이전 1 2 3 4 5  다음»