본문 바로가기

이팩티브 자바

[Effective] equals & hashCode 이번 글에서는 equals와 hashCode에 대해서 다뤄볼 예정이다. ❗ equals 메서드란? 두 인스턴스의 주소 값을 비교하여 같은 인스턴스인지를 확인하고, 같다면 true 다르다면 false를 반환한다. public class EX { public static void main(String[] args) { Person test1 = new Person("Test1"); Person test2 = new Person("Test1"); System.out.println(test1.equals(test1)); // true System.out.println(test2.equals(test1)); // false } public static class Person { private String name.. 더보기
[Effective] try-with-resources BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String str = in.readLine(); 다음과 같이 BufferedReader를 통해 입력을 받으려고 할 때, 고려 사항 IOException이 발생할 수 있다. close()를 통해 직접 닫아줘야 하는 자원이다. 그래서, try-finally 문법을 사용해 해당 코드를 수정한다면 다음과 같이 수정할 수 있다. public String Input() throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { return in.readLine().. 더보기
[Effective] 정적 팩터리 메서드 정적 팩터리 메서드는 객체 생성 역할을 하는 클래스 메서드이다. public class Car { private String car; // 생성자 public Car(final String car) { this.car = car; } // 정적 팩터리 메서드 public static Car from(final String name) { return new Car(name); } } ❗생성자 대신 정적 팩터리 메서드를 사용해야 하는 이유 ‼장점 1. 이름을 가질 수 있다. 정적 팩터리 메서드를 사용하면, 메서드 이름에 객체의 생성 목적을 담아낼 수 있다. public static Car createDefaultCar() { return new Car("Default"); } 위와 같은 형식으로 객체를 생성.. 더보기