****Generic
1. 용도
1) 특정 타입 ( 객체 타입 ) 을 미리 검사
- 사전에 잘못된 데이터 타입을 미리 체크
2) C++ 의 Template 과 비슷한 기능\
2. 사용문법
클래스 <객체타입> 참조변수 = new 클래스의 생성자 <객체타입>
3. 작성문법
class 클래스이름 <특정 키워드>{
}
----------------------------------------------------------------------
package Generic;
import java.util.Vector;
public class GenericTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Vector vec = new Vector(); 문자열 타입만 저장할수 있지만, 숫자를 써도 오류가 나지않아 미스코딩을 하기 쉽다.
Vector<String> vec = new Vector<String>(); //Vector 값에 제너릭 으로 String 을줘서 문자열만 받도록 했다 밑의 숫자100 란에 오류가생긴다.
vec.add("hell O");
vec.add("HHell o");
vec.add("hEEll o");
//...
//vec.add(100);
/* String str = null; //비어있는값 - 창조할 주소가 없을때. 0값 이 아니라 無값
for (int i=0 ; i<vec.size(); i++){
str = (String)vec.get(i);
System.out.println(str);
*/
//for(변수 : 배열 또는 컬렉션)
//배열이나 컬렉션 안에있는 데이터를 모두 사용할 때 까지 반복을 계속한다.
for (String str : vec){
System.out.println(str);
}
}
}
----------------------------------------------------------------------
package Generic;
class GenericDemo <T>{
private T value;
// 내가 원하는 타입을 실행중에 결정을 할수 있게, 동적 바인딩.
// 데모클래스 자체를 제너릭 으로 생성하여야 한다.
public GenericDemo(T i){
value = i;
}
public T getValue() {
return value;
}
}
public class GenericTest2 {
public static void main(String[] args) {
// TODO Template 의 용도
GenericDemo<Integer> demo1 = new GenericDemo(100); //<>안에는 객체타입만 올수 있음 int 형의 wrap 클래스
System.out.println(demo1.getValue()); //래퍼클래스 integer Double String
GenericDemo <Double>demo2 = new GenericDemo(3.14);
System.out.println(demo2.getValue());
GenericDemo <String>demo3 = new GenericDemo("Generic Test...");
System.out.println(demo3.getValue());
}
}
----------------------------------------------------------------------
----------------------------------------------------------------------
=======================================================================
****예외처리
1. 예외(에러)가 발생했을 경우 / 에러에 대한 제어권을 시스템 ( JVM ) 이 아니라 개발자가 가질수 있게 하는 방법.
2. 왜?
1) 예외 가 발생했을 때 메세지에 대한 표현 문제
2) 프로그램의 비정상적 종료
----------------------------------------------------------------------
package prjException;
public class ExcTest1 {
public static void main ( String args []){
int[] arr = new int [3];
System.out.println("예외처리 첫번쨰 테스트...");
int i;
try{
arr[7] = 100;
i= 10/0;
}
catch( ArrayIndexOutOfBoundsException err){
System.out.println("배열넘침잼 : " + err.toString());
}
catch(IndexOutOfBoundsException err){
System.out.println("아오바에서잡음 ㅋ");
}
catch(RuntimeException err){
System.out.println("런타임에서잡음 ㅋ");
}
catch(Exception err){
System.out.println("!!!!!!!!!!!!!!!!!!!!!!예외발생!!!!!!!!!!!!!!!!!!!!!!");
}
System.out.println("이게 보이냐?");
}
}
----------------------------------------------------------------------
package prjException;
import java.io.IOException;
public class ExcTest2 {
public static void main(String[] args) {
// TODO 예외처리 두번째 예제
System.out.println("한문자 입력 : ");
char input =' ';
try {
input = (char) System.in.read();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("What charactor U input : " + input);
}
}
----------------------------------------------------------------------
----------------------------------------------------------------------
3. 주요 키워드
1) try
2) catch
3) throw
-예외를 던진다.
-용도 : 테스트 나 처리위치 변경
-한개만 던질수 있다
-반드시 블럭(메서드) 안에 선언되어야 한다
4) throws
-예외들을 던진다
-용도 : 대신 처리를 부탁
-여러개 던질수 있다
-반드시 블럭 (메서드)바깥에 선언되어야 한다
5) finally
----------------------------------------------------------------------
package prjException;
public class ThrowTest {
public static void main(String[] args) {
// TODO Throw 예제
try{
System.out.println("여기는 try블럭..");
throw new ArithmeticException("일부러 예외발생시킴..");
}
catch ( ArithmeticException err){
System.out.println("ArithmeticException err occur");
System.out.println(err.getMessage());
}
System.out.println("End of try/catch Test");
}
}
----------------------------------------------------------------------
package prjException;
public class ThrowsTest {
static void second() throws ArithmeticException {
System.out.println("second() 호출");
throw new ArithmeticException();
}
static void first() throws Throwable {
System.out.println("first() 호출");
second();
}
// try{
// }
// catch(ArithmeticException err)
// System.out.println("first에서 작동");
// }
// 세컨드 에서 발생한 문제를 throws 로 퍼스트로넘겼음
public static void main(String args[]) throws Throwable {
// TODO Thows 예제
try {
first();
}
catch (Exception err) {
System.out.println("메인으로넘어감");
}
catch (Throwable err){
System.out.println("throwable 처리됨");
}
}
}
----------------------------------------------------------------------
----------------------------------------------------------------------
4. try~ catch block
try{
예외가 발생할 가능성이 있는 코드
}
catch (매개변수){
처리
}
-----------------------------------
try {
...
}
catch(...){ 자식클래스(구체적이다)
... ↓
}
catch(...){
... ↓
}
catch(...){ 부모클래스 (자식이못찾으면 뭐라도걸러내긴한다) Exception / Throwable
...
}
5. Throwable
get massage
printstackTrace
toString
**************
io
1.Stream 구조
1) 단방향
2) 순차적
3) 지연 발생 가능
4) 어떤 장치를 사용하던간에 사용법은 동일
5) 자바에서는 java.io라는 패키지에서 제공
2. 자바에서 제공하는 Stream 방식
1) Byte Stream 방식
-input Stream
read()
-output Stream
write()
2) Character Stream 방식
-Reader
read()
Writer
write()
3) PrintStream 방식
print().
println().
3. 자주 사용할 만한 클래스들
1)FileInputStream, FileOutputStream
2)DataInputStream, DataOutputStream
----------------------------------------------------------------------
package ByteStream;
import java.io.IOException;
public class ByteTest1 {
public static void main(String[] args) throws IOException {
// TODO Byte Stream 예제 1
System.out.println("문자열 입력 (10문자까지) :");
byte data[] = new byte[10];
System.in.read(data);
for (int i=0; i<data.length; i++)
System.out.println((char)data[i]);
}
}
----------------------------------------------------------------------
package ByteStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteTest2 {
public static void main(String[] args) throws IOException {
// TODO ByteStream 방식 예제 2
streamTest(System.in,System.out);
}
public static void streamTest(InputStream is, OutputStream os )throws IOException{
int input = 0;
while(true) {
input = is.read();
if (input == -1) // -1 이라는 값은 ctrl + z 일때 -1이 전달되고 실제로 -1 을쓰면 2글자로인식한다
break;
//System.out.println((char)input);
os.write((char) input);
}
}
}
----------------------------------------------------------------------
package ByteStream;
import java.io.FileInputStream;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) throws IOException{
// TODO 파일로부터 입력받아 모니터로 출력
FileInputStream fin = new FileInputStream("E:\\Test1.txt" );
int input = 0;
while(true) {
input = fin.read();
if (input == -1) // -1 이라는 값은 ctrl + z 일때 -1이 전달되고 실제로 -1 을쓰면 2글자로인식한다
break;
System.out.write((char)input);
}
}
}
----------------------------------------------------------------------
댓글 없음:
댓글 쓰기