Tumgik
spiranac-blog · 6 years
Text
Collection, Map 사용 시 팁 (Tips for using Collection, Map in Java)
백엔드를 자바로 개발하면서 제일 많이 사용하는 것이 무엇이냐고 물으면 나는 컬렉션 프레임워크를 제일 많이 사용한다고 대답할 거 같다. 컬렉션만큼 자바에서 데이터를 효율적으로 저장하는 인터페이스는 없다고 생각한다.
그만큼 자바에서 컬렉션을 잘 사용할줄 안다는 것은 데이터를 효율적으로 저장하고 꺼내 쓴다는 것을 의미한다. 자바로 개발을 하면서 컬렉션 사용 관련 팁을 까먹지 않기 위해 작성한다.
If you ask what is the most use of backend development in Java language, I would say that I use the collection framework the most. I do not think there is an interface that efficiently stores data in Java as well as collections.
Knowing that using collections well in Java means storing and retrieving data efficiently. Write it to avoid missing tips on using the Collection in Java.
new 키워드로 객체 생성 및 선언 시 구현 클래스가 아닌 인터페이스로 선언
When creating and declaring an object with the new keyword, declared as an interface rather than a implementation class.
나는 보통 맵을 선언할 때 다음과 같은 방식으로 선언했다. I usually declare a map in the following way
HashMap<String, Object> map = new HashMap<>();
실제로 이클립스에서는 위처럼 구현 클래스로 객체를 선언해줘야 경고 메시지가 나타나지 않는다. 인터페이스로 선언을 하면 객체 타입을 확실하게 지정해야 한다고 경고메시지가 나타난다. 객체 타입을 명확하게 생성하는 장점이 있지만 문제점은 map 객체에 다른 Map 구현 객체를 대입할 때 발생한다. In fact, Eclipse does not warn you if you declare an object as an implementation class like above. When you declare it as an interface, you are warned that you must specify the object type explicitly. Creating explicitly an object type has advantage, but the problem arises when assigning another Map implementation object to the map object.
HashMap<String, String> map = new HashMap<>(); map = new TreeMap<>();
위처럼 코드를 작성하면 에러가 당연히 발생한다. HashMap 객체에 TreeMap 객체를 대입할 수 없으니까. 객체를 다음과 같이 생성하면 에러를 방지할 수 있다. (경고는 뜨겠지만) If you write the code like above, the error naturally occurs. You can not assign a TreeMap object to a HashMap object.
Map<String, String> map = new HashMap<>(); map = new TreeMap<>();
이렇게 하면 map 객체에 어떠한 map 구현클래스도 대입할 수 있게 된다. 어떤 map 구현 클래스가 대입될 지 확실하지 않은 상황에는 위처럼 인터페이스로 객체를 선언하자. This allows any map implementation class to be assigned to the map object. If you are not sure which map implementation class to assign, declare the object as an interface as above.
함수(메서드)의 리턴 타입은 인터페이스로 선언
The return type of a function (method) is declared as an interface
이것도 첫 번째 팁과 그 목적이 비슷하다. 다음의 함수가 있다고 가정하자. This is also similar to the first tip. Suppose you have the following function:
public static HashMap<String, String> getUnknownMap(){ HashMap<String, String> returnHashMap = new HashMap<>(); TreeMap<String, String> returnTreeMap = new TreeMap<>(); // 일련의 로직... // some logic... return returnHashMap; }
위처럼 작성하면 리턴되는 객체의 타입이 HashMap으로 강제가 된다. 그래서 returnTreeMap 객체를 리턴시키면 에러가 발생한다. 하지만 다음과 같이 리턴 타입을 인터페이스로 선언하면 HashMap, TreeMap 상관없이 어떠한 map 구현클래스든 리턴이 가능하다. If you write like this, the type of the returned object will be enforced by HashMap. So returning the returnTreeMap object will result in an error. However, if you declare a return type as an interface like the following, any map implementation class can be returned regardless of HashMap or TreeMap.
public static Map<String, String> getUnknownMap(){ HashMap<String, String> returnHashMap = new HashMap<>(); TreeMap<String, String> returnTreeMap = new TreeMap<>(); // 일련의 로직... // some logic... return returnHashMap; }
만약 함수나 메서드가 어떠한 타입의 객체가 리턴될 지 명확하지 않을 때 인터페이스로 리턴 타입을 명시하면 좋다. 하지만 위 방식도 단점이 존재한다. 다음의 소스를 보자 If the function or method is not clear what type of object to return, you can specify the return type in the interface. However, there is also a drawback to this approach. Let's look at the following sources.
public static void main(String[] args) { TreeMap<String, String> map = getUnknownMap(); } public static Map<String, String> getUnknownMap(){ HashMap<String, String> returnHashMap = new HashMap<>(); TreeMap<String, String> returnTreeMap = new TreeMap<>(); // 일련의 로직... // some logic... return returnHashMap; }
위 소스는 main 함수에서 에러가 난다. 함수에서 리턴은 HashMap을 리턴하고 있지만 main 함수에서는 TreeMap 객체에 getUnknownMap 함수의 리턴값을 넣고 있으니까.. 위처럼 소스가 간략할때에는 에러를 찾기 쉽고, 수정도 쉽지만 복잡한 소스에서 위 같은 에러가 나면 찾기도 힘들고 수정하는 데에도 많은 수고가 든다. The above source has an error in the main function. The return from the function returns a HashMap, but the main function puts the return value of the getUnknownMap function in the TreeMap object. When the source is as simple as above, it is easy to find the error and modify it. But complex source takes a lot of effort to fix it.
결론은 상황에 따라서 리턴 타입을 인터페이스로 할 지 구현클래스로 할 지 정한 후 함수를 정의하자. The conclusion is that you define the return type as the interface or the implementation class as the situation before define the function.
0 notes
spiranac-blog · 6 years
Text
IntelliJ에서 Eclipse 단축키 설정 (Setting Eclipse shortcuts in IntelliJ)
IntelliJ라는 IDE가 있다는 것을 알게 된 지는 한 2년쯤 된 것 같다. Eclipse를 사용하다가 IntelliJ를 사용하면 신세계가 열린다는 개발자들의 간증을 보고 나도 IntelliJ를 사용하고 싶었지만, 유료라는 점 때문에 사용하기가 꺼려졌다. Eclipse도 불편하지 않았기 때문에 무료 IDE를 놔두고 굳이 유료 제품을 선택할 이유는 없었기 때문이다.
어느 날 문득 한 가지 IDE 뿐 아니라 여러 IDE 사용에 익숙해지면 좋을 거 같다는 생각을 했다. 어떤 개발환경에서도 당황하지 않고 개발이 가능하다는 점이 멋있어 보였다. 그래서 IntelliJ를 결제하고 사용해보기로 했다. IntelliJ 공식 홈페이지를 가보면 알겠지만 월별, 연별 결제가 가능하다. 나는 혹시나 IntelliJ에 적응을 못하고 Eclipse로 다시 돌아갈까봐 안전하게 월 결제로 사용하기로 했다.
IntelliJ는 Eclipse와 기본적인 기능 별 단축키가 다르다. 그래서 IntelliJ에서 Eclipse의 단축키를 사용할 순 없을까 하고 구글링을 하다가 방법을 찾았다. 까먹지 않기 위해 기록한다.
It has been about two years since I discovered that there is an IDE called IntelliJ. I wanted to use IntelliJ when I saw the reviews of developers, 'If use IntelliJ instead of using Eclipse, New world is open', but I was reluctant to use it because of the fee. Eclipse was not inconvenient, so there was no reason to choose a paid product instead of a free IDE.
One day I thought that it would be nice to get used to using not only one IDE but also several IDEs. It seemed nice to be able to develop without any embarrassment in any development environment. So I decided to pay and try to use IntelliJ. When you visit IntelliJ official website, monthly, yearly payment is possible. I decided that buy monthly payment. Because I would not be able to adapt to IntelliJ and go back to Eclipse.
IntelliJ differs from Eclipse in its basic functional shortcuts. So I figured out how to use Eclipse's shortcuts in IntelliJ by google search. I record for not forget.
File - Settings... 클릭
Click File - Settings menu.
Keymap 카테고리 클릭
Click Keymap category.
Keymap 콤보박스를 Default에서 Eclipse로 변경 (MAC OS용 이클립스 단축키로 변경할 수도 있다. MAC OS를 사용해보지 않아서 윈도우의 이클립스와 MAC OS의 이클립스가 단축키가 다른가보다)
Change Keymap combobox Default into Eclipse. (You can also change it to an Eclipse shortcut for MAC OS. Eclipse for Windows OS and Eclipse for MAC OS have different shortcuts.)
이후 OK나 Apply 버튼을 눌러 적용하면 된다.
And then, apply by pressing OK or Apply button.
0 notes