국비학원 12일차 : DateType, CollectionClass, Generic

Digeut·2023년 3월 10일
0

국비학원

목록 보기
12/44

DateType

Time패키지

특정 날짜 혹은 시간 가져오기

LocalDateTime localDateTime = LocalDateTime.now();

// .get***();
int year = localDateTime.getYear();
int month = localDateTime.getMonthValue();
System.out.println(month); //3
Month enumMonth = localDateTime.getMonth();
System.out.println(enumMonth); //MARCH
int dayOfYear = localDateTime.getDayOfYear();
System.out.println(dayOfYear); //이번년도에서 몇번째 날인지 //69
int dayOfMonth = localDateTime.getDayOfMonth();
System.out.println(dayOfMonth); //월기준몇번째 날인지 //10
DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
System.out.println(dayOfWeek); //FRIDAY
			
boolean isLeapYear = localDate.isLeapYear(); //윤달 표시
			
int hour = localDateTime.getHour();
int minute = localDateTime.getMinute();
int second = localDateTime.getSecond();
int nano = localDateTime.getNano();

특정 날짜 및 시간 변경(직접변경, 더하기, 빼기)

LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
🟡LocalDateTime localDateTimeOf = 
	LocalDateTime.of(localDateOf, localTimeOf);
    //2022.12.25 12:40데이터
System.out.println(localDateTimeOf);

// 직접변경 : .with***(int타입 데이터);
// 더하기 - 빼기 : .plus***(long 타입 데이터)
//				  .minus***(long 타입 데이터);
//date 2개 time 2개 해보기
//localDateTime = localDateTime.withYear(2012); //직접변경
localDateTime = localDateTime.withYear(2012).plusWeeks(4).minusHours(9);
//더하기 빼기

//localDateTime = localDateTime.withDayOfYear(1); //1월 1일 //직접변경
localDateTime = localDateTime.withDayOfYear(1).plusMinutes(50)
				.minusNanos(50000); //더하기 빼기
//localDateTime = 이 부분을 추가하니까 지정한 날짜로 밑에 출력
//안하면 현재시간으로 출력 왜지?🤔
			
//일정관리하는거 만들땐 필요하다
			
//일반적으로 Date타입으로 저장해서 사용한다
//데이트 타입을 연산시에 인스턴스 만들어주는게 좋다🤔
Instant instant =
localDateTime.atZone(ZoneId.systemDefault()).toInstant();
//ZoneID를 통해서 타임존 정보를 넘기면 원하는 지역의 시간을 얻을 수 있다
Date datetime = Date.from(instant);
System.out.println(datetime);

Timer - TimerTask

특정 작업을 지연시킬때 사용
TimerTask 클래스를 상속받아서 run 메서드를 구현(오버라이딩)

class Delay extends TimerTask/*abstract으로 구성*/{

	@Override
	public void run() {
		//지연시킬 메서드 작성
		System.out.println("지연!");
	}
	
}
	//추상메서드 run
	//선언부만 작성이 되어있고 구현부는 작성되어 있지 않은 메서드
	//⭐해당 클래스를 상속받은 자손클래스에서 구현을 필수로 요구함

public class EtcClass {

	public static void main(String[] args) {
		
		//Timer 클래스의 인스턴스로 TimerTask 구현체를 실행
		Timer timer = new Timer(true); 
        //객체 생성하고 원하는시간 파라미터로 작성
		Delay delay = new Delay();
		timer.schedule(delay, 500); //500은 5초
		
//		//지연걸어주기?
//		for(int index = 0 ; index < 100000000; index++) {
//			int a = 10;
//			int b = 20;
//			a += b;
//			b -= a;
//		}
		
		System.out.println("완료");
		
        //예외잡기 try catch문
		try {
		Thread.sleep(1000);}
		catch(InterruptedException e) {
			e.printStackTrace();
		}

BigDecimal

//정확한 소수점 연산을 하기 위한 클래스
double double1 = 9.45112548855;
double double2 = 1.35224458811;
System.out.println(double1 + double2);
		
BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(double1)); 
						//안에 문자열을 넣어줘야한다
BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(double2));
System.out.println(bigDecimal1.add(bigDecimal2));

DecimalFormat

//일정형식으로 데이터 출력해주는 클래스
DecimalFormat decimalFormat = new DecimalFormat("$###,###,###.00");
System.out.println(decimalFormat.format(10_000_000)); //문자열로 출력
//$10,000,000.00 형태로 출력

Collection Framework

컬렉션 개체
배열형태의 데이터를 보다 편하게 사용할 수 있도록 해주는 클래스의 집합

Set

집합의 개념, 중복을 허용하지 않고 순서가 없는 형태
순서가 없기 때문에 인덱스 사용 불가능

Set은 Interface, 이 Set을 받아 클래스로 구현한것이 HashSet, TreeSet
interface를 구현시 사용하는 implements는 이미 사용되서 구현된것.

HashSet

// HashSet<E> : 중복을 허용하지 않고 순서가 없는 형태
Set</*참조타입이 와야함*/Integer> integerSet = new HashSet<Integer>();
	integerSet.add(43);
	integerSet.add(51);
	integerSet.add(562);
	integerSet.add(56);
	integerSet.add(18);
	integerSet.add(69);
	integerSet.add(35);
    
for(Integer item : integerSet) {
	System.out.println(item);
} //순서없이 마구잡이로 출력
//iterator : 컬렉션의 요소에 접근해서 반복적인 작업을 할 때 도움을 주는 객체
Iterator<Integer> iterator = integerSet.iterator();
//이터레이터 사용해서 접근시 보통 while문 쓴다	
//549812135 이터레이터가 뭉쳐놓고
//처음 커서에서 다음에 값이 있는지 확인하는데 hasNext
//next는 처음 커서에서 다음 값을 반환해주고 다음 값으로 넘어감
		
	while(iterator.hasNext()) {
		System.out.println(iterator.next());
	} //이렇게 해도 마구잡이로 출력된다

TreeSet

// TreeSet<E> : 중복 허용하지않고 순서가 없는 형태 + 정렬
//데이터를 정렬하는 방식은 기존의 데이터와 비교하여 
//작은 값은 왼쪽, 큰 값은 오른쪽에 추가
Set<Integer> treeSet = new TreeSet<Integer>();
	treeSet.add(521);
	treeSet.add(542);
	treeSet.add(1);
	treeSet.add(852);
	treeSet.add(666);
		
for(Integer item : treeSet) {
	System.out.println(item);
	} //1 521 542 666 852 정렬

List

데이터를 일렬로 나열한 구조
순서가 존재하고 중복이 허용(배열)

ArrayList

List는 interface, 이 List를 받아 클래스로 구현한게 ArrayList

//ArrayList<E> : 순서 존재하고 중복이 허용된 '배열'
List/*인터페이스*/<String> list = new ArrayList<String>(); 
//배열과 달리 길이 지정하지 않고쓴다
list.add("apple"); //인덱스 0에 사과있었는데 밑에서 바나나를 0에 추가하면 밀려난다.
list.add(0,"banana"); //특정인덱스에 값을 넣겠다(추가)
		
list.set(0, "BaNaNa"); //값을 변경
		
String removeItem = list.remove(1); //특정 인덱스 값 삭제, 
									//삭제라기보단 보따리 안에서 꺼내주는것
System.out.println(removeItem); //apple 꺼내옴
		
System.out.println(list.toString()); //[BaNaNa]형태 출력
		
for(int index = 0 ; index < list.size() ; index++) { 
	//배열의 경우 length 쓰는데 컬렉션들은 size
	System.out.println(list.get(index)/*get써서 접근한다*/);
	}

LinkedList

//LinkedList<E> : 순서가 존재하고 중복이 허용된 '배열' +
//				  각 요소가 이전 요소와 다음 요소의 주소를 같이 가지고 있음
//				  검색속도가 빠름
		
List<Integer> arrayList = new ArrayList<Integer>();
List<Integer> linkedList = new LinkedList<Integer>();

//arrayList
long startTime = System.currentTimeMillis(); //작업시간 측정시 사용 

for(int integer = 0 ; integer < 100_000 ; integer++) {
	arrayList.add(0, integer); //0부터 integer까지 더해준다
	}
long endTime = System.currentTimeMillis();
		
System.out.println("Array List 작업시간 : " + (endTime - startTime));

//LinkedList
startTime = System.currentTimeMillis(); //작업시간 측정시 사용 

for(int integer = 0 ; integer < 100_000 ; integer++) {
	linkedList.add(0, integer); //0부터 integer까지 더해준다
	}

endTime = System.currentTimeMillis();
		
System.out.println("Linked List 작업시간 : " + (endTime - startTime));
		
//특정한 하나의 값을 찾아가는건 ArrayList가 더 빠르다 

//출력 결과
//Array List 작업시간 : 331
//Linked List 작업시간 : 3

Map

key와 value가 하나의 쌍으로 저장되는 구조
순서가 존재하지 않음, 단 key를 이용해서 특정한 value를 가져올수 있음

키와 값을 쌍으로 저장하는 구조
클래스 인스턴스 선언시 부를때 속성필드명으로 가져오는것과 유사!

Map도 interface로 구성되어 있으므로 클래스로 구현해주는 작업이 필요하다 HashMap은 구현된 클래스

//HashMap<E/*키에대한 제너릭*/, E/*벨류에 대한 제너릭*/>
Map<String, String> hashMap = new HashMap<String, String>();
		
hashMap.put("key", "value");
hashMap.put("apple", "사과"); 
		
//값을 꺼내고 싶을땐
System.out.println(hashMap.get("apple")); //키에 대한 값을 반환해준다
		
//클래스처럼 쓰일 수 있어서 hashMap은 잘 안쓰는게 좋다
//(클래스에 변수 선언해서 가져와 쓰는거랑 유사함)
//hash는 특정한 타입을 미리 지정해서 입력해줘야한다 
//여러가지를 넣으려고 object로 넣어야하는데
//꺼내올때도 object로 꺼내야하기때문에 정확한 데이터 타입을 가져오기 어려워진다

lotto 응용 (지난번에는 배열만 이용함)

//Lotto 응용 (배열말고 다른거 사용)
//중복제거 + 정렬! -> treeSet 사용
Set<Integer> lotto = new TreeSet<>();
		
//반복돌리기
while(lotto.size()<6) {
	Random random = new Random();
	int randomNumber = random.nextInt(45)+1;
	lotto.add(randomNumber);
}
		
System.out.println(lotto.toString());

Generic

다양한 타입을 다루는 메서드나 클래스에 컴파일 시 타입을 체크하는 기능
컴파일 시 타입을 체크하기때문에 유연하게 개발을 할 수 있음.
제네릭(Generic)은 클래스 내부에서 지정하는 것이 아닌 외부에서 사용자에 의해 지정되는 것을 의미한다
타입 파라미터로 명시할 수 있는 것은 참조 타입(Reference Type)밖에 올 수 없다.

Queue : first in first out

파이프처럼 입구와 출구가 따로따로 나눠져있는 형태
다음 이전이 무엇인지 값을 다 가지고 있다.

Stack : first in Last out, Last in first out

비커처럼 입구와 출구가 하나인 형태

class GenericClass<D> { //E또는T많이 사용, 지금은 D사용
	
    //인스턴스 선언
	boolean 🟣status;
	String 🟣message;
//	Object data; //나중에 어떤 타입으로 받을지 알기가 어렵다
	D 🟣data; /*나중에 데이터 타입 지정하겠다*/
	//API 에 대한 결과를 전달해줄때 사용한다
	
    //get 메서드
	static <D> GenericClass<D> getInstance(boolean 🟢status, 
    								String 🟢message, D 🟢data){
		//static뒤에 <D> 안해주면 뒤에서 D를 받지 못한다
        //non-static 타입으로 static 타입 받을수 없다는 오류 뜸
		//인스턴스 생성
        GenericClass<D> instance = new GenericClass<>();
		instance.🟣status = 🟢status;
		instance.🟣message = 🟢message;
		instance.🟣data = 🟢data;
		
		return instance;
		}
}

public class Generic {

	public static void main(String[] args) {
		
        //클래스에서 선언한 제네릭 받아와서 사용 여기서 데이터 타입지정
        //GenericClass 인스턴스 생성시 반환 타입 정한다
        GenericClass<Integer> generic1 = new GenericClass<>();
		GenericClass<String> generic2 = new GenericClass<>();
		GenericClass<> generic3 = new GenericClass<>();
		
//		generic1.data = "sddfd"; //이건 int로 받으니까 문자열 받을수 없다!
		generic1.data = 50;
		generic2.data = "diq"; //왜 안받아질까.. 분명히 스트링으로 했는데 
        //-> .data를 안넣었다!
//		generic3.data = "diq"; 얘는 그럼 왜 안될까
		
		GenericClass<> generic4 = 
        		GenericClass.getInstance(true, "message", "String");
	}

}
profile
개발자가 될 거야!

0개의 댓글