포스코DX X 비트교육센터 6기 - Calendar, 자료구조


final

  • final class : 상속 금지
  • final void m(){} : 오버라이드 금지

Calendar

  • DATE은 가급적 사용하지 말고, Calendar을 사용해라.
package chapter04;

import java.util.Calendar;

public class CalendarTest {
	public static void main(String[] args) {
		
		System.out.println("=====방법1=====");
		
		Calendar cal = Calendar.getInstance();
		printDate(cal);
		
		
		System.out.println("=====방법2=====");
		
		cal.set(Calendar.YEAR, 2023);
		cal.set(Calendar.MONTH, 11); //12월, MONTH-1
		cal.set(Calendar.DATE, 25);
		
		printDate(cal);
		
		System.out.println("=====방법3=====");
		
		cal.set(2000, 11, 03);
		cal.add(Calendar.DATE, 10000); //10000일 지난 날
		printDate(cal);
	}

	private static void printDate(Calendar cal) {
		final String[] DAYS= { "일", "월", "화", "수", "목", "금", "토" };
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH); //0~11. +1 필요
		int date = cal.get(Calendar.DATE);
		int day = cal.get(Calendar.DAY_OF_WEEK); //1(일)~7(토). 
		int hour = cal.get(Calendar.HOUR);
		int minute = cal.get(Calendar.MINUTE);
		int second = cal.get(Calendar.SECOND);
		
		System.out.println(
				(year) + "/" + (month + 1) + "/" + date + " " + DAYS[day-1] + "요일 " + hour + ":" + minute + ":" + second);
	}
}

자료구조 - Collection Framework

  • 자료가 모여있는 것 Collection : 순서 O List, 순서 X set
  • 자료가 모아져 있지 않는 것 key, value가 mapping : map

  • Iterator란 자바의 컬렉션(Collection)에 저장되어 있는 요소들을 순회하는 인터페이스

image

image

  • 삽입삭제 多 : 링크드 리스트 -> arrayList는 안 좋음. 배열이기 때문

  • 백터 : 동기화 처리가 되어있음. 멀티스레드 환경이라면 벡터쓰면 편함.

Synchronous 동기 / Asynchronous 비동기

모든 프로그램은 client server로 이루어져있다.

  • 동기란? - 소켓
    • client가 server에게 메시지를 보냄
    • server가 DB에 가서 메시지에 알맞는 일을 하는데, 이는 시간이 걸린다.
    • client는 응답이 올때까지 기다렸다가(Blocking) 결과를 받으면 그제야 client는 다시 일을 한다.

    • ex. 화장실 : 한 사람이 들어가서 문을 잠그면, 사용중임을 표시하고, 다른 사람(thread)이 왔을 때 사용중임을 확인하고 sleep함. 화장실은 공유자원이고 사람들은 여러 쓰레드임.
  • 비동기란? - 자바스크립트
    • client가 server에게 메시지를 보냄
    • server가 DB에 가서 메시지에 알맞는 일을 하는데, 이는 시간이 걸린다.
    • client 코드는 그냥 쭉 실행하고 결과가 나오면 받는다. 코드가 쭉 흘러간다. 코드가 멈추지 않는다.

Vector

  • Vector
package collection;

import java.util.Enumeration;
import java.util.Vector;

public class VectorTest01 {
	public static void main(String[] args) {
		Vector<String> v = new Vector<>();
		
		v.addElement("둘리");
		v.addElement("마이콜");
		v.addElement("도우너");
		
		// 순회01
		for(int i=0; i<v.size(); i++) {
			String s = v.elementAt(i);
			System.out.println(s);
		}
		
		// 삭제
		v.removeElementAt(2);
		
		// 순회02
		Enumeration<String> e = v.elements();
		//순회객체는 한 번만 가능함.
		while(e.hasMoreElements()) {
			String s = e.nextElement();
			System.out.println(s);
		}
		
		
		
	}
}

  • List
package collection;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class VectorTest02 {
	
	public static void main(String[] args) {
		List<String> list = new Vector<>();
		
		list.add("둘리");
		list.add("마이콜");
		list.add("도우너");
		
		// 순회01
		for(int i= 0; i<list.size(); i++) {
			String s = list.get(i);
			System.out.println(s);
		}
		
		// 삭제
		list.remove(2);
		
		// 순회02
		Iterator<String> it = list.iterator();
		while(it.hasNext()) {
			String s = it.next();
			System.out.println(s);
		}
		
		// 순회03
		for(String s : list) {
			System.out.println(s);
		}
		
		
	}

}

LinkedList

package collection;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class LinkedListTest {
	public static void main(String[] args) {
		List<String> list = new LinkedList<>();

		list.add("둘리");
		list.add("마이콜");
		list.add("도우너");

		// 순회01
		for (int i = 0; i < list.size(); i++) {
			String s = list.get(i);
			System.out.println(s);
		}

		// 삭제
		list.remove(2);

		// 순회02
		Iterator<String> it = list.iterator();
		while (it.hasNext()) {
			String s = it.next();
			System.out.println(s);
		}

		// 순회03
		for (String s : list) {
			System.out.println(s);
		}
	}
}

ArrayList

package collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListTest {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();

		list.add("둘리");
		list.add("마이콜");
		list.add("도우너");

		// 순회01
		for (int i = 0; i < list.size(); i++) {
			String s = list.get(i);
			System.out.println(s);
		}

		// 삭제
		list.remove(2);

		// 순회02
		Iterator<String> it = list.iterator();
		while (it.hasNext()) {
			String s = it.next();
			System.out.println(s);
		}

		// 순회03
		for (String s : list) {
			System.out.println(s);
		}
	}

}

HashSet

package collection;

import java.util.HashSet;
import java.util.Set;

public class HashSetTest {
	public static void main(String[] args) {
		Set<String> s = new HashSet<>();
		
		String s1 = new String("도우너");
		String s2 = new String("도우너");
		
		s.add("둘리");
		s.add("마이콜");
		s.add("또치");
		
		s.add("또치"); //자료구조는 무조건 동질성 비교이다. 같은 것을 넣지 않음.
		s.add(s1); //자료구조는 무조건 동질성 비교이다. 같은 것을 넣지 않음.
		s.add(s2); //값 기반임. 주소는 XXX
		
		System.out.println(s.size());
		System.out.println(s.contains(s2));
		System.out.println(s.size());
		
		// 순회
		for(String str : s) {
			System.out.println(str);
		}
		
	}
}

  • hashcode와 equals를 바꿈으로써 구구단 수정하기
package collection;

import java.util.HashSet;
import java.util.Set;

public class HashSetTest02 {
	public static void main(String[] args) {
		Set<Gugudan> set = new HashSet<>();
		
		//결과가 같은 경우, 안 들어가도록 하기.
		set.add(new Gugudan(2, 3));
		set.add(new Gugudan(9, 9));
		set.add(new Gugudan(3, 2));
		
		for(Gugudan g: set) {
			System.out.println(g);
		}
		
		
	}
}

package collection;

import java.util.Objects;

public class Gugudan {
	private int lValue;
	private int rValue;
	
	public Gugudan() {
		// TODO Auto-generated constructor stub
	}

	public Gugudan(int lValue, int rValue) {
		super();
		this.lValue = lValue;
		this.rValue = rValue;
	}

	@Override
	public String toString() {
		return "Gugudan [lValue=" + lValue + ", rValue=" + rValue + "]";
	}

	@Override
	public int hashCode() {
		return Objects.hash(lValue * rValue);
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Gugudan other = (Gugudan) obj;
		return lValue * rValue == other.lValue * other.rValue;
	}
	
	
	
}

HashMap

package collection;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapTest {
public static void main(String[] args) {
	Map<String, Integer> m = new HashMap<>();
	
	m.put("one", 1);  //auto boxing
	m.put("two", 2);
	m.put("three", 3);
	
	int i = m.get("one"); //auto unboxing
	int j = m.get(new String("one"));
	System.out.println(i + ":" + j);
	
	m.put("three", 3333);
	System.out.println(m.get("three"));
	
	// 순회
	Set<String> s = m.keySet();
	for(String k : s) {
		System.out.println(m.get(k));
	}
}
}

Stack

package collection;

import java.util.Stack;

public class StackTest {
	public static void main(String[] args) {
		Stack<String> s = new Stack<>();
		
		s.push("둘리");
		s.push("마이콜");
		s.push("도우너");
		
		while(!s.isEmpty()) {
			String str = s.pop();
			System.out.println(str);
		}
		
		//비어있는 경우, 예외 발생
		// s.pop();
		
		s.push("둘리");
		s.push("마이콜");
		s.push("도우너");
		
		System.out.println(s.pop());
		System.out.println(s.peek());
		System.out.println(s.pop());
		
	}
}

Queue

package collection;

import java.util.LinkedList;
import java.util.Queue;

public class QueueTest {
public static void main(String[] args) {
	Queue<String> q = new LinkedList<>();
	
	q.offer("둘리");
	q.offer("마이콜");
	q.offer("또치");
	
	while(!q.isEmpty()) {
		String s = q.poll();
		System.out.println(s);
	}
	
	q.offer("둘리");
	q.offer("마이콜");
	q.offer("또치");
	
	System.out.println(q.poll());
	System.out.println(q.peek());
	System.out.println(q.poll());
	System.out.println(q.poll());
	
	// 비어있는 경우에는 null을 반환한다.
	System.out.println(q.poll());
	
}
}

io

  • Byte
    • InputStream : FileInputStream, filterInputStream(보조스트림)
    • OutputStream : FileOuputStream, filterOutputStream(보조스트림)
  • Char + Reader : FileReader , InputStreamReader(보조스트림) + Writer : outputStreamWriter(보조스트림)

  • ioFileCopy 코드
package io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileCopy {

	public static void main(String[] args) {
		InputStream is = null;
		OutputStream os = null;
		
		try {
			is = new FileInputStream("loopy.jpg");
			os = new FileOutputStream("loopy.copy.jpg");
				
			int data = -1;
			while((data = is.read()) != -1) {
				os.write(data);
			}
		} catch (FileNotFoundException e) {
			System.out.println("file not found: " + e);
		} catch (IOException e) {
			System.out.println("error: " + e);
		} finally {
			try {
				if(is != null) {
					is.close();
				}
				if(os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
  • FileReader Test
package io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

public class FileReaderTest {

	public static void main(String[] args) {
		Reader in = null;
		InputStream is = null;
		
		try {
			in = new FileReader("test.txt");
			
			int count = 0;
			int data = -1;
			
			while((data = in.read()) != -1) {
				System.out.print((char)data);
				count++;
			}
			
			System.out.println("");
			System.out.println("count:" + count);
			System.out.println("==========================");
			
			count = 0;
			data = -1;
			
			is = new FileInputStream("test.txt");
			while((data = is.read()) != -1) {
				System.out.print((char)data);
				count++;
			}
			
			System.out.println("");
			System.out.println("count:" + count);
			
		} catch (FileNotFoundException e) {
			System.out.println("file not found: " + e);
		} catch (IOException e) {
			System.out.println("error: " + e);
		} finally {
			try {
				if(in != null) {
					in.close();
				}
				if(is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
  • 보조스트림

< 보조스트림 중, Buffer 을 사용하면 좋은 이유 >

한 바이트씩 바로바로 보내는 것이 아니라 버퍼에 담았다가 한번에 모아서 보내는 방법이므로
시스템 콜의 횟수가 줄어들게 되고 성능상 이점이 생기게 된다.

OS 레벨에 있는 시스템 콜의 횟수 자체를 줄이기 때문에 성능이 빨라지는 것이다.

https://resilient-923.tistory.com/129
package io;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderTest {

	public static void main(String[] args) {
		BufferedReader br = null;
		
		try {
			// 기반 스트림
			FileReader fr = new FileReader("./src/main/java/io/FileReaderTest.java");
		
			// 보조 스트림
			br = new BufferedReader(fr);
			
			String line = null;
			while((line = br.readLine()) != null) {
				System.out.println(line);
			}
		} catch (FileNotFoundException e) {
			System.out.println("File Not Found:" + e);
		} catch (IOException e) {
			System.out.println("error:" + e);
		} finally {
			try {
				if(br != null) {
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
package io;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedOutputStreamTest {
	public static void main(String[] args) {
		BufferedOutputStream bos = null;
		
		try {
			// 기반 스트림
			FileOutputStream fis = new FileOutputStream("hello.txt");
			
			// 보조 스트림
			bos = new BufferedOutputStream(fis);
			
			//for(int i = 'a'; i <= 'z'; i++)
			for(int i = 97; i <= 122; i++) {
				bos.write(i);
			}
		} catch (FileNotFoundException e) {
			System.out.println("File Not Found: " + e);
		} catch (IOException e) {
			System.out.println("error: " + e);
		} finally {
			try {
				if(bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Scanner

Scanner는 java.util에 있다. io로 입력받고 쓰는게 어려워서 편리하게 쓰라고 이렇게 있다.

posix(프로그램 표준)

stdin(키보드 연결), stdout(콘솔연결), stden(콘솔에러연결)에 모두 연결되어있어야한다는 규약이 있음.