[Java] Data types 2

·2022년 10월 16일

JAVA

목록 보기
3/10

Array

배열은 길이를 변경할 수 없으므로 고려해서 작성한다.

int[] odds = {1, 3, 5, 7, 9};
String[] names = new String[5];
// 초기값 없는 배열 선언 시에는 길이를 반드시 설정
String[] weeks = {"월", "화", "수", "목", "금", "토", "일"};
String monday = String[0]; // 배열 접근
int week = weeks.length; // week = 7

 


List

List는 인터페이스로, 이를 구현한 자료형으로 ArrayList, Vector, LinkedList 등이 있다.
배열과 유사하지만, 크기가 동적으로 변한다.

ArrayList

import java.util.ArrayList;

ArrayList 사용을 위해서는 import가 필요하다.

ArrayList<String> names = new ArrayList<>();
names.add("Mina");		// Mina
names.add("Jisu");		// Mina, Jisu
names.add(0, "Yeon");	// Yeon, Mina, Jisu

String thirdName = names.get(2); // Jisu

이 외에도 size, contains, remove 등의 메소드가 있다.
또한 이미 존재하는 배열을 ArrayList로 변환할 수도 있다.

Arrays의 메소드를 사용하기 위해서는

import.java.util.Arrays;
String[] data = {"Mina", "Jisu", "Yeon"};
ArrayList<String> names = new ArrayList<>(Arrays.asList(data));

String.join을 이용해 각 요소 사이 원하는 구분자를 추가해 하나의 문자열로 만들 수 있다.

ArrayList<String> heights = new ArrayList<>(Arrays.asList("155", "170", "192"));
String result = String.join(",", heights); // 155,170,192

리스트의 sort 메소드를 사용하면 각 요소를 순서대로 정렬하는 것도 가능하다.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class Example {
	public static void main(String[] args) {
    	ArrayList<String> heights = new ArrayList<>(Arrays.asList("155", "170", "192");
        heights.sort(Comparator.naturalOrder()); // 오름차순 정렬
        heights.sort(Comparator.reverseOrder()); // 내림차순 정렬
    }
}

 


Map

데이터셋을 전달할 때, Key : Value 형식이 요구되는 경우가 종종 발생한다.
Map 구조는 이러한 대응관계를 쉽게 표현할 수 있도록 한다.
리스트나 배열처럼 순서에 따라 요소의 값을 가져오지 않고, key를 이용하게 된다.
Map 역시 인터페이스로 HashMap, LinkedHashMap(Sequential), TreeMap(저장과 동시에 오름차순 정렬) 등으로 구현되어 있다.

HashMap

import java.util.HashMap;

public class Example {
	public static void main(String[] args) {
    	HashMap<String, String> map = new HashMap<>();
        map.put("name", "YEON");
        map.put("height", "200");
        System.out.println(map.get("name"));
        System.out.println("wrong height value : " + map.remove("height"));
    }
}	

 


Set

집합을 표현하는 자료형으로 Set이 존재한다. 역시 인터페이스로, HashSet, LinkedHashSet, TreeSet 등이 존재한다.
Set 자료형은 집합을 표현하는 것, 즉 값의 중복을 허용하지 않는다. 따라서 필터로도 사용될 수 있다.

import java.util.Arrays;
import java.util.HashSet;

public class Example {
	public static void main(String[] args) {
    	HashSet<String> set1 = new HashSet<>(Arrays.asList("A", "b", "c", "c")); // A, b, c
        set1.add("x"); // x 추가
        HashSet<String> set2 = new HashSet<>(Arrays.asList("A", "B", "C));
        HashSet<String> intersection = new HashSet<>(set1);
        intersection.retainAll(set2); // 교집합 -> "A"
    }
}	

이 외에도 addAll(합집합 또는 여러 값 추가), remove, removeAll(차집합) 등의 메소드가 있다.

 


Enum

Enum은 상수 집합으로, 관련이 있는 상수들의 집합을 저장한다.

public class Pay {
	public final static Pay CARD = new Pay();
    public final static Pay MONEY = new Pay();
    public final static Pay SMARTPAY = new Pay();
}
// ------------------- //
public enum Pay {
	CARD, MONEY, SMARTPAY;
}

위와 같이 코드를 간결하게 하면서 가독성을 좋게 하고, 인스턴스 생성과 상속을 방지할 수 있다. 또한 enum임을 명시하여 구현의 의도를 바로 파악할 수 있다. 이를 활용하여 특정 상황에서 데이터 관리를 DB 대신 코드 내에서 수행하게 하는 등의 활용이 가능하다. 기본적으로 직렬화가 가능한 타입이기 때문에 싱글톤을 구현하는 데 있어 좋은 방법으로 사용될 수 있다.

 


형변환과 final

String aStr = "123";
int aInt = Interger.parseInt(aStr);

int bInt = 123;
String bStr1 = "" + bInt;
String bStr2 = String.valueOf(bInt);
String bStr3 = Integer.toString(bInt);

String cStr = "12.34";
double cDouble = Double.parseDouble(cStr);
int cInt = (int) cDouble; //타입캐스팅 필요
double d = cInt; // 정수->실수에는 타입캐스팅 요구되지 않음

final 키워드를 설정하면 자료형에 값을 단 한 번만 설정할 수 있도록 해 수정이 불가능하도록 만든다.

 


이 글은 점프 투 자바를 읽고 스터디한 글입니다.

0개의 댓글