Enum, Generic, 예외처리, List, Set, Hashmap에 대해 배웠다. 배웠는데..
갑자기 난이도 쫙 올라간 느낌
열심히 하는 것 말고 답이 없긴하지....ㅋㅋ
열거형enum : 서로 연관된 상수의 집합.각 상수에는 자동적으로 0부터 시작하는 정수값이 할당된다.
enum Days {SUN, MON, TUE, WED, THU, FRI, SAT}
public class test01 {
public static void main(String[] args) {
Days favoriteDays = Days.FRI;
System.out.println(favoriteDays); //FRI
System.out.println(Days.valueOf("SUN"));//SUN
Days[] allDays = Days.values(); //모든 열거 객체를 배열로 리턴
for (Days day : allDays) {
System.out.printf("%s = %d%n", day.name(), day.ordinal());
//name() : 문자열 리턴
//ordinal() : 인덱스 리턴
// SUN = 0
// MON = 1
// TUE = 2
// WED = 3
// THU = 4
// FRI = 5
// SAT = 6
}
}
}
제네릭generic : 타입을 구체적으로 지정하지 않고, 나중에 지정할 수 있도록 일반화해 두는 것
클래스의 객체를 생성해서 데이터타입으로 지정하는 방식이므로 기본 타입을 사용할 수 없다 > 기본 타입의 경우는 래퍼 클래스를 사용한다
클래스 변수에는 제네릭으로 타입 매개변수를 사용할 수 없다.
래퍼 클래스wrapper class : 기본 타입의 데이터를 객체로 포장해주는 클래스
short >> SHORT / int >> Integer / char >> Character
박싱 : 기본 타입 >> 래퍼 클래스
언박싱 : 래퍼 클래스 >> 기본 타입
제네릭에도 다형성을 적용할 수 있다.
package test02;
interface Drink {}
class Coffee implements Drink {}
class Americano extends Coffee implements Drink {}
class IcedAmericano<T extends Coffee & Drink> {
//클래스를 상속받으면서 인터페이스를 구현할 수도 있다. 이 때에는 &를 사용하여, 인터페이스보다 클래스가 앞에 오도록 주의하도록 하자
private T cup;
public <T> void methodIcedAmericano(T t) {
//제네릭 메서드의 매개 변수 T와 클래스의 매개 변수 T는 별개의 T이다.
}
}
class Cup<T> {
private T cup;
public Cup(T cup) {
this.cup = cup;
}
}
class Drinks{
public static void hasCaffeine(Cup<? extends Coffee> cup) {
System.out.println("Caffeine");
}
public static void canItBeHot(Cup<? super Americano> cup) {
System.out.println("hot");
}
}
public class test {
public static void main(String[] args) {
IcedAmericano<Coffee> icedAmericano = new IcedAmericano<>();
IcedAmericano<Americano> americano = new IcedAmericano<>();
Drinks.hasCaffeine(new Cup<Coffee>(new Coffee())); //Caffeine
Drinks.canItBeHot(new Cup<Americano>(new Americano()));//hot
// Drinks.canItBeHot(new Cup<IcedAmericano>(new IcedAmericano())); 불가능
}
}
와일드카드 ?로 제한을 둘 수도 있다
<? extends T> : T와 T의 하위 클래스만 받을 수 있다
<? super T> : T와 T의 상위 클래스만 받을 수 있다
에러는 발생 시점에 따라 컴파일 에러(신택스 에러Synstax Errors)와 런타임 에러로 나뉜다.
예외exception : 잘못된 사용 혹은 코딩으로 인한 미약한 수준의 오류. 수습이 가능
에러Error : 복구하기 어려운 수준의 심각한 오류. OutOfMemoryError, StackOverflowError 등이 있다.
예외는 발생 시 그 즉시 프로그램을 종료하는데, 예외 처리를 해줌으로써 종료를 피할 수 있다.
try {일단 실행할 코드}
catch (Exception e) {try 이후 ()안의 예외가 발생할 경우 실행할 코드}
finally {예외가 발생 하던 안하던 실행할 코드}
throw : 고의적으로 예외 발생 시키기
throws : 예외 전가 시키기. 예외 처리의 책임을 호출한 메서드에 전가시킨다.
public class Throws {
public static void main(String[] args) {
try {
divide(2, 0);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
public static int divide(int num1, int num2) throws ArithmeticException {
if (num2 == 0) {
throw new ArithmeticException("0으로 못나눔");
}
return num1 / num2;
}
}
///0으로 못나눔
List : 데이터 순서 O 중복 저장 O
객체를 인덱스로 관리
-ArrayList : 객체가 인덱스로 관리된다. 데이터가 연속적으로 존재한다. > 탐색이 빠르다
그러나 중간 삽입, 삭제가 느리다
-LinkedList : ArrayList와 달리 불연석적으로 존재.
자기 자신이 가리켜야할 데이터의 주소와, 자신과 연결된 다음 노드의 주소값으로 구성된다.
탐색은 느리지만 중간 삽입, 삭제가 빠르다.
-Stack
-Vector
Set : 데이터 순서 X 중복 저장 X (List와 함께 Collection 인터페이스)
-HashSet : 객체의 해시코드를 hashCode()를 통해 얻어내, 중복 개체는 저장 X
-TreeSet : 이진 탐색 트리
Map : 데이터 순서X 키 중복 X 값 중복 O
Entry객체 : key + value
key가 다르면 value의 값이 같아도 다른 entry로 간주한다.
-HashMap : 해시 함수를 통해 키와 값이 저장될 위치를 정한다. 사용자는 그 위치를 알 수 없다.
Hashing을 사용해, 많은 양의 데이터를 검색하는데 성능이 좋다.
키와 값을 쌍으로 저장하기 때문에 iterator()를 직접 호출할 수 없다. 두 개를 Set로 만들어 반복자를 호출할 수 있다.
-HashTable
-TreeMap
-Properties
package List;
import java.util.ArrayList;
public class ArrayListEx {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Spring");
list.add("Summer");
list.add("Fall");
System.out.println(list.size());//3
System.out.println(list.get(0));//Spring
for (String str : list) {
System.out.println(str); //Spring\nSummer\nFall\n
}
list.remove(1);
System.out.println(list.get(1));//Fall
}
}
Iterator : 컬렉션에 저장된 요소를 순차적으로 읽어온다.
import java.util.HashSet;
import java.util.Iterator;
public class hashtest {
public static void main(String[] args) {
HashSet<String> seasons = new HashSet<String>();
seasons.add("Spring");
seasons.add("Summer");
seasons.add("Fall");
seasons.add("Spring"); //중복. 저장x
seasons.add("Winter");
Iterator iterator = seasons.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
/*
Winter
Summer
Fall
Spring
*/
import java.util.TreeSet;
public class TreeSetEx {
public static void main(String[] args) {
TreeSet<String> seasons = new TreeSet<>();
seasons.add("Spring");
seasons.add("Summer");
seasons.add("Fall");
seasons.add("Winter");
System.out.println(seasons);//[Fall, Spring, Summer, Winter]
System.out.println(seasons.first());//Fall //가장 작은 요소 반환
System.out.println(seasons.last());//Winter
System.out.println(seasons.higher("Fall"));//Spring
System.out.println(seasons.subSet("Spring", "Winter")); //[Spring, Summer] //지정된 범위에 속하는 요소 반환
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class HashTest {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Spring", 10);
map.put("Summer", 20);
map.put("Fall", 30);
map.put("Winter", 40);
System.out.println(map.size()); //4
System.out.println(map.get("Spring")); //10
Set<String> keySet = map.keySet();
Iterator<String> keyIterator = keySet.iterator();
while(keyIterator.hasNext()) {
String key = keyIterator.next();
Integer value = map.get(key);
System.out.println(key + value); //Winter40\nSummer20\nFall30\nSpring10\n
}
map.remove("Winter");
System.out.println(map.size());//3
}
}