'Java'에 해당되는 글 3건
Effective Java, 2nd Edition :: 2009/08/18 12:54
Joshua Bloch의 Effective Java Second Edition (2008)의 목차만 따와 봤다.

1 Introduction
2 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
3 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
4 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
5 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
6 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
7 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
8 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
9 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
10 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
11 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
Appendix: Items Corresponding to First Edition
References
Index
===================================
CHAPTER 1 개요
CHAPTER 2 객체의 생성과 소멸
[항목 1] 생성자 대신 static 팩토리(factory) 메소드 사용을 고려하자
[항목 2] 생성자의 매개변수가 많을 때는 빌더(builder)를 고려하자
[항목 3] private 생성자나 enum 타입을 사용해서 싱글톤의 특성을 유지하자
[항목 4] private 생성자를 사용해서 인스턴스 생성을 못하게 하자
[항목 5] 불필요한 객체의 생성을 피하자
[항목 6] 쓸모 없는 객체 참조를 제거하자
[항목 7] 파이널라이저(finalizer)의 사용을 피하자
CHAPTER 3 모든 객체에 공통적인 메소드
[항목 8] equals 메소드를 오버라이딩 할 때는 보편적 계약을 따르자
[항목 9] equals 메소드를 오버라이드 할 때는 hashCode 메소드도 항상 같이 오버라이드 하자
[항목 10] toString 메소드는 항상 오버라이드 하자
[항목 11] clone 메소드는 신중하게 오버라이드 하자
[항목 12] Comparable 인터페이스의 구현을 고려하자
CHAPTER 4 클래스와 인터페이스
[항목 13] 클래스와 그 멤버의 접근성을 최소화하자
[항목 14] public 클래스에서는 public 필드가 아닌 접근자(accessor) 메소드를 사용한다
[항목 15] 가변성을 최소화 하자
[항목 16] 가급적 상속(inheritance)보다는 컴포지션(composition)을 사용하자
[항목 17] 상속을 위한 설계와 문서화를 하자. 그렇지 않다면 상속의 사용을 금지시킨다
[항목 18] 추상 클래스보다는 인터페이스를 사용하자
[항목 19] 타입을 정의할 때만 인터페이스를 사용하자
[항목 20] 태그(tagged) 클래스보다는 클래스 계층을 사용하자
[항목 21] 전략을 표현할 때 함수 객체를 사용하자
[항목 22] static 멤버 클래스를 많이 사용하자
CHAPTER 5 제네릭(Generics)
[항목 23] 새로 작성하는 코드에서는 원천(raw) 타입을 사용하지 말자
[항목 24] 컴파일 경고 메시지가 없게 하자
[항목 25] 배열보다는 List를 사용하자
[항목 26] 제네릭 타입을 애용하자
[항목 27] 제네릭 메소드를 애용하자
[항목 28] 바운드 와일드 카드를 사용해서 API의 유연성을 높이자
[항목 29] 타입 안전이 보장되는 혼성(heterogeneous) 컨테이너의 사용을 고려하자
CHAPTER 6 열거형(Enum)과 주석(Annotation)
[항목 30] int 상수 대신 enum을 사용하자
[항목 31] 서수(序數) 대신 인스턴스 필드를 사용하자
[항목 32] 비트(bit) 필드 대신 EnumSet을 사용하자
[항목 33] 서수(序數) 인덱스 대신 EnumMap을 사용하자
[항목 34] 인터페이스를 사용해서 확장 가능한 enum을 만들자
[항목 35] 작명 패턴보다는 주석(annotation)을 사용하자
[항목 36] Override 주석을 일관성 있게 사용하자
[항목 37] 타입 정의는 표시 인터페이스를 사용하자
CHAPTER 7 메소드(method)
[항목 38] 매개 변수가 유효한지 검사하자
[항목 39] 필요하면 방어 복사본을 만들자
[항목 40] 메소드 시그니처를 신중하게 설계하자
[항목 41] 오버로딩(overloading)을 분별력 있게 사용하자
[항목 42] 가변 인자(varargs)를 분별력 있게 사용하자
[항목 43] null대신 비어있는 배열이나 컬렉션을 반환하자
[항목 44] 외부에 제공하는 모든 API 요소에 대해 문서화 주석을 넣자
CHAPTER 8 프로그래밍 일반
[항목 45] 지역 변수의 유효 범위를 최소화 하자
[항목 46] 종전의 for 루프보다는 for-each 루프를 사용하자
[항목 47] 라이브러리를 배우고 사용하자
[항목 48] 정확한 계산에는 float나 double 타입을 쓰지 말자
[항목 49] 박스화 기본형보다는 기본형을 사용하자
[항목 50] 다른 타입을 쓸 수 있는 곳에서는 String 사용을 피하자
[항목 51] 문자열 결합의 성능 저하를 주의하자
[항목 52] 객체 참조는 그 객체의 인터페이스 타입으로 하자
[항목 53] 리플렉션보다는 인터페이스를 사용하자
[항목 54] 네이티브 메소드를 분별력 있게 사용하자
[항목 55] 잘 판단해서 최적화하자
[항목 56] 보편화된 작명 규칙을 따르자
CHAPTER 9 예외(Exceptions)
[항목 57] 예외 상황에서만 예외를 사용하자
[항목 58] 복구 가능 상황에는 checked 예외를 사용하고 런타임 예외는 프로그램 에러에 사용하자
[항목 59] checked 예외의 불필요한 사용을 피하자
[항목 60] 표준 예외를 사용하자
[항목 61] 하위 계층의 예외 처리를 신중하게 하자
[항목 62] 메소드가 던지는 모든 예외를 문서화하자
[항목 63] 실패 상황 정보를 상세 메시지에 포함하자
[항목 64] 실패 원자성을 갖도록 노력하자
[항목 65] 예외를 묵살하지 말자
CHAPTER 10 동시성(Concurrency)
[항목 66] 공유하는 가변 데이터에 접근 시 동기화하자
[항목 67] 지나친 동기화는 피하자
[항목 68] 스레드 그룹보다는 실행자와 작업을 사용하자
[항목 69] wait와 notify 대신 동시성 유틸리티를 사용하자
[항목 70] 스레드 안전을 문서화 하자
[항목 71] 늦 초기화를 분별력 있게 사용하자
[항목 72] 스레드 스케줄러에 의존하지 말자
[항목 73] 스레드 그룹을 사용하지 말자
CHAPTER 11 직렬화(Serialization)
[항목 74] Serializable 인터페이스를 분별력 있게 구현하자
[항목 75] 독자적인 직렬화 형태의 사용을 고려하자
[항목 76] 방어 가능한 readObject 메소드를 작성하자
[항목 77] 인스턴스 제어에는 readResolve 메소드보다 enum 타입을 사용하자
[항목 78] 직렬화된 인스턴스 대신 직렬화 프록시의 사용을 고려하자
부록:제1판과의 항목 대비
참고문헌
찾아보기
시스템 명령을 실행해서 결과 뿌리기 :: 2007/05/11 11:51
import java.io.*;
public class SystemExec {
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(args);
InputStream in = p.getInputStream();
for(int ch; (ch = in.read()) != -1;)
System.out.write(ch);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
System.exit(0);
}
}
|
실행결과: > java SystemExec ls / |
자바 정규표현식 :: 2007/04/30 15:51
자바 정규표현식
자바의 정규표현식은 J2SE 1.4 부터 지원되지 시작했습니다. 관련된 주요 클래스들는 java.util.regex 패키지에 있습니다.
Pattern 클래스
Pattern 객체는 Perl 문법과 비슷한 형태로 정의된 정규표현식을 나타냅니다. 문자열로 정의한 정규표현식은 사용되기 전에 반드시 Pattern 클래스의 인스턴스로 컴파일되어야 합니다. 컴파일된 패턴은 Matcher 객체를 만드는 데 사용되며, Matcher 객체는 임의의 입력 문자열이 패턴에 부합되는 지 여부를 판가름하는 기능을 담당하합니다. 또한 Pattern 객체들은 비상태유지 객체들이기 때문에 여러 개의 Matcher 객체들이 공유할 수 있습니다.
Matcher 클래스
Matcher 객체는 특정한 문자열이 주어진 패턴과 일치하는가를 알아보는데 이용됩니다. Matcher 클래스의 입력값으로는 CharSequence라는 새로운 인터페이스가 사용되는데 이를 통해 다양한 형태의 입력 데이터로부터 문자 단위의 매칭 기능을 지원 받을 수 있습니다. 기본적으로 제공되는 CharSequence 객체들은 CharBuffer, String, StringBuffer 클래스가 있습니다.
Matcher 객체는 Pattern 객체의 matcher 메소드를 통해 얻어진다. Matcher 객체가 일단 만들어지면 주로 세 가지 목적으로 사용됩다.
- 주어진 문자열 전체가 특정 패턴과 일치하는 가를 판단(matches).
- 주어진 문자열이 특정 패턴으로 시작하는가를 판단(lookingAt).
- 주어진 문자열에서 특정 패턴을 찾아낸다(find).
이들 메소드는 성공 시 true를 실패 시 false 를 반환합니다.
또한 특정 문자열을 찾아 새로운 문자열로 교체하는 기능도 제공됩니다. appendRepalcement 메소드는 일치하는 패턴이 나타날 때까지의 모든 문자들을 버퍼로 옮기고 찾아진 문자열 대신 교체 문자열로 채워 넣습니다. 또한 appendTail 메소드는 캐릭터 시퀀스의 현재 위치 이후의 문자들을 버퍼에 복사해 넣습니다. 다음 절에 나오는 예제 코드를 참고하도록 합시다.
CharSequence 인터페이스
CharSequence 인터페이스는 다양한 형태의 캐릭터 시퀀스에 대해 일관적인 접근 방법을 제공하기 위해 새로 생겨났으며, java.lang 패키지에 존재합니다. 기본적으로 String, StringBuffer, CharBuffer 클래스가 이를 구현하고 있으므로 적절한 것을 골라 사용하면 되며, 인터페이스가 간단하므로 필요하면 직접 이를 구현해 새로 하나 만들어도 됩니다.
자바 정규표현식 사용 예제
기본 사용 예제
소스
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 정규표현식 기본 사용 예제
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest01 {
public static void main(String[] args) {
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
if (b) {
System.out.println("match");
} else {
System.out.println("not match");
}
}
} |
결과
match |
문자열 치환하기
소스
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 문자열 치환 예제
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest02 {
public static void main(String[] args) {
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
// or
//String str = m.replaceAll("dog");
//System.out.println(str);
}
} |
결과
one dog two dogs in the yard |
이메일주소 유효검사
소스
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 이메일주소 유효검사
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest03 {
public static boolean isValidEmail(String email) {
Pattern p = Pattern.compile("^(?:\\w+\\.?)*\\w+@(?:\\w+\\.)+\\w+$");
Matcher m = p.matcher(email);
return m.matches();
}
public static void main(String[] args) {
String[] emails = { "test@abc.com", "a@.com", "abc@mydomain" };
for (int i = 0; i < emails.length; i ++) {
if (isValidEmail(emails[i])) {
System.out.println(emails[i]);
}
}
}
} |
결과
test@abc.com |
HTML 태그 제거
소스
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* HTML 태그 제거
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest04 {
public static String stripHTML(String htmlStr) {
Pattern p = Pattern.compile("<(?:.|\\s)*?>");
Matcher m = p.matcher(htmlStr);
return m.replaceAll("");
}
public static void main(String[] args) {
String htmlStr = "<html><body><h1>Java2go.net</h1>"
+ " <p>Sehwan@Noh's Personal Workspace...</p></body></html>";
System.out.println(stripHTML(htmlStr));
}
} |
결과
Java2go.net Sehwan@Noh's Personal Workspace... |
HTML 링크 만들기
소스
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* HTML 링크 만들기
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest05 {
public static String linkedText(String sText) {
Pattern p = Pattern.compile(
"(http|https|ftp)://[^\\s^\\.]+(\\.[^\\s^\\.]+)*");
Matcher m = p.matcher(sText);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb,
"<a href='" + m.group()+"'>" + m.group() + "</a>");
}
m.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) {
String strText =
"My homepage URL is http://www.java2go.net/home/index.html.";
System.out.println(linkedText(strText));
}
}
|
결과
My homepage URL is |
금지어 필터링하기
소스
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 금지어 필터링하기
*
* @author Sehwan Noh <sehnoh at java2go.net>
* @version 1.0 - 2006. 08. 22
* @since JDK 1.4
*/
public class RegExTest06 {
public static String filterText(String sText) {
Pattern p = Pattern.compile("fuck|shit|개새끼", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(sText);
StringBuffer sb = new StringBuffer();
while (m.find()) {
//System.out.println(m.group());
m.appendReplacement(sb, maskWord(m.group()));
}
m.appendTail(sb);
//System.out.println(sb.toString());
return sb.toString();
}
public static String maskWord(String word) {
StringBuffer buff = new StringBuffer();
char[] ch = word.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (i < 1) {
buff.append(ch[i]);
} else {
buff.append("*");
}
}
return buff.toString();
}
public static void main(String[] args) {
String sText = "Shit! Read the fucking manual.";
System.out.println(filterText(sText));
}
} |
결과
S***! Read the f***ing manual. |

