'프로그래밍'에 해당되는 글 363건

  1. 2012.07.29 예외처리(Exception), try catch finally
  2. 2012.07.29 난수구하기 및 수학함수
  3. 2012.07.29 java 시간 날짜 처리
  4. 2012.07.29 String class, String buffer
  5. 2012.07.29 boxing, unboxing, wrapperClass
  6. 2012.07.29 object클래스
  7. 2012.07.29 제너릭
  8. 2012.07.28 collection값 빼오기
  9. 2012.07.28 map실습
  10. 2012.07.28 ArrayList실습

* 예외 : 프로그래머가 원하지 않는 방향으로 가는 것.
* 오류 : 프로그램이 정상적으로 실행하지 못하는 상황.
  1. Error : 심각한 오류(프로그램을 멈춰야 하는 오류) - H/W적 오류
  2. Exception : mild오류(심각하지 않음 오류) - s/w적오류(실행시 정상적인흐름(programmer가 의도한 흐름)으로 가지 못한 상황.

* Exception Handling(예외처리)
- 예외가 발생되었을때 프로그램이 정상적으로 처리되도록 해주는 것.

Throwable - 오류의 최상위
^       ^
|       |
Error   Exception
           ^
           |
     ---------------
     |             |
   Runtime        나머지
   (unchecked)    (checked)

 

 

 


- Exception - unchecked 계열(Handleing(처리) : compiler가 신경쓰지 않음), checked 계열(compiler가 체크)
- unchecked : 컴파일러가 Exceoption 처리여부를 체크 않함
  발생이유 : code상의 문제 때문에 발생 (100퍼센트 실행 시 오류가 남. 코드를 수정해 주는 것이 맞음)
             compiler의 check가 불가능한 경우.
             -> 처리(Handling)보다는 code 수정

- checked 계열 Exception : 컴파일러가 Exception 처리여부를 check
                         하지 않았을 경우 컴파일 에러 발생
  발생이유 :  code상 문제가 아니라 user가 잘못 사용하였거나 실행 환경상 문제로 발생
  - 발생 확률 :  50 : 50
  -> 처리가 필요.

* 오류가 나면 그자리에서 처리 하는게 아니라 오류가 나는 곳의 상위에서 처리한다.
* throw, throws, try, catch, finally
throw :  오류를 발생시키는 것
throws, try, catch, finally : 오류를 처리하는 것.(try, catch, finally는 셋이 같이 붙어 다닌다. )
* Exception class 정의하는 법.

* Exception class 작성(교재 P537)
  1. checked :  Exception을 extends
     unchecked : RuntimeException을 extends
  2. public class
  3. no-arg 생성자
     String 인수로 받는 생성자
  4. 필요한 Attribute, 메소드를 구현.
     이름 ; ~Exception

* project : day24
  package : exception.sample
  class : ExceptionTest
          Divide
          ZeroDivideException

 


package exception.sample;

public class ExceptionTest {
 public static void main(String[] args){
 Divide d = new Divide();
 int result = 0;
 try{
  result = d.divide(10,0);
 }catch(ZeroDivideException ze){
      System.out.println("오류가 발생했습니다.");
      try {
   result = d.divide(10, 5);
  } catch (ZeroDivideException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 System.out.println("나눈 결과 : "+result);
 }
}

---------

 

package exception.sample;

public class Divide {
 
 public int divide(int num1, int num2) throws ZeroDivideException{
   //num1을 num2로 나눈 값(몫)을 return
  if(num2==0){ //예외상황
   throw new ZeroDivideException();
   
  }
  return num1/num2;
 }
}


-----------

package exception.sample;
/*
 * Exception 클래스
 * 0으로 숫자를 나눴을 때의 예외상황을 표현하기 위한 클래스
 */
public class ZeroDivideException extends Exception{
 public ZeroDivideException(){}
 public ZeroDivideException(String message){
  super(message);
 }
}


------------
==========================================================
* Exception 발생(던진다) - throw (호출해준 사람한테 예외를 던져준다.)
  구문 :  throw Throwable의 객체;

num2 = 0;

* 예외처리 : throws - 예외발생할 메소드를 호출한 caller메소드에서 처리하도록 하는 것.
             try,catch,finally - 발생한 예외를 직접처리하는 것.

 
- 메서드 구문 :  [제한자] return type 이름([매개변수들]) throws [ExceptionType, . . .]{}
ex :  public void go() throws AEception, BException{}


                 
* 메소드 overriding - 하위 class에서 부모의 메소드 재정의
        (instance 메소드)
- 규칙 - 전제; 이름동일
  1. return type, 매개변수가 동일
  2. 하위의 접근제한자가 상위 것과 같거나 더 넓어야한다.
* 3. 부모가 throws 한것만 할 수 있다.( exception )
     -> 부모에서 throws 한것 안 할 수 있다.


* Exception

     ^
     |
  --------
  |       |
AException BException
  |      
------
|    |
A1Exception A2Exception


Super

public void go() throws AE{}

Sub
public void go(){} ok
public void go() throws AE,BE{} no
public void go() throws A1E,A2E extends Super(){}  ok

- try, catch, finally - 오류처리

try{
 오류(예외)발생 가능성이 있는 코드 ->throw
                                          ->메소드 호출 -> throws

}catch(예외(오류) type 변수선언){
 처리코드;
}

* ex :
try{
 1.AE
 2.BE
 3.CE
}catch(AE a){
 4.
}catch(BE b){
 5.
}catch(CE c){
 6.
}
 7.

2. BE발생

1.->2.X->5.->7. //이렇게 이동. 만약 위에 것에 오류가 나면 아래 있는 것이 실행할 의미가 없으면 이렇게 하고, 아랫것도 실행해야 되면 try{}catch(){}를 따로 잡아줘야 한다.


*

project : day24
package : exception.trycatch
class : ExceptionTest1


package exception.trycatch;

public class ExceptionTest1 {
 public static void main(String[] args) {
  /*
   * uncheck 계열의 Exception
   * ArrayIndexOutOfBoundsException - 배열의 index 범위를 넘었을때 발생
   * NullPointerException - null값을 가진 변수의 instance멤버 호출시 발생
   * ArithmethicException - 산술 연산상 문제 발생시 발생(0으로 나눈 경우)
   */
  String str = null;
  try{
  System.out.println(str.concat("def"));//100%이므로 수정하는게 맞지만 연습용으로 try{}catch(){}를 쓴다.
  }catch(NullPointerException ne){
   System.out.println("NullPointerException 발생");
   
  }try{
  System.out.println(10/0);
  }catch(ArithmeticException ae){
   System.out.println("ArithmeticException 발생");
  }
  int[] arr = {10,20,30};
  try{
  System.out.println(arr[10]);
  }catch(ArrayIndexOutOfBoundsException arre){
   System.out.println("ArrayIndexOutOfBoundsException 발생");
  }
  System.out.println("메인메소드 종료");
 }
}


---------
============================================================================
*
package exception.trycatch;

public class ExceptionTest2 {
 public static void main(String[] args) {
  String str = null;
  try{
  str.concat("def");
  int result = 10/0;
  int arr[]= {10,20,30};
  System.out.println(arr[0]);
  
  int i = Integer.parseInt("abcde");
  }catch(NullPointerException e){
   System.out.println("NullPointerException발생");
  }catch(ArithmeticException ae){
   System.out.println("ArithmeticException발생");
  }catch(ArrayIndexOutOfBoundsException ae){
   System.out.println("ArrayIndexOutOfBoundsException발생");
  }catch(Exception e){ //모든 Exception의 상위 개념으로 위에서 잡은 것 말고는 다 여기서 잡는다.
   System.out.println("Exception e");
  }
  System.out.println("메인메소드 종료");
 }
 
}
----------------------
==========================================================================

--------------------
=============================================================================


 
* 2012-3-27

 오류                                                
          |
----------------------
|                     |
에러                 예외
심각한H/w적           S/W적

 

 Throwable
            |
--------------------------
|                         |
Error                    Exception
                          |
                   --------------------------
                   |                         |
     unchecked : RunTimeException   checked : exception(checked 는 사용자가 메뉴얼 대로 사용하지 않거나 호출이 잘못되었을 시 사용하는 exception이다.)

* 오버라이딩 규칙에 걸려서 exception을 던지지 못할 경우에는 Runtime계열의 Exception을 만들어 던진다.
ex : ABCException a = new ABCException();
     WrapperException we = new WrapperException(a);
     throw new we;

* exception은 잘못된 상황이 나오면 잘못된 상황을 표현하기 위한 class(exception)를 만들면된다.
  
* RuntimeException도 컴파일시 구문에 적어주지 않아도 에러가 나지 않지만 구문만 보고도 사용자가 Exception이 난다는 것을 알아야 하기 때문에 구문에 throws를 사용해서 나타내준다.
ex :

public void b() throws NullPointerException{

 throw new NullPointerException();
}

* 상속구조의 Exception을 잡을 시에는 하위 것부터 잡아야 한다. 왜냐하면 상위를 먼저 잡으면 상위에서 예외를 다 처리하여 하위 예외는 왜 썼냐고 물으면서 에러를 내기 때문이다.
* catch안에 아무것도 구현안해도 예외처리를 한것이기는 하나 로그를 남겨야 한다. (오류를 남겨 두지 않으면 프로그램이 아무 이상 없는 것으로 보이는데 프로그램이 실행이 안되는 경우가 생길 수 있다.)

* Exception 발생
public void addProduct()throws SameIDException{
  throw new SameIDException();
}
  메소드 호출
try{
pm.addProduct();
}catch(SameIDException se){
}


* 개발에서는 catch에 printStackTrace();를 한다.

*
try{
 예외가 날 확률이 있는 코드
}catch(  e){
 예외처리
}finally{
무조건 실행
}

----------------------------

try{ 1->4->5
1       - AE발생
2
3
}catch(AE e){
4
}
5

-----------------------------


try{
1     
2
3
}catch(AE e){
4
}finally{
5
}

예외가 없으면 1->2->3->5
1번에서 예외가 나면 1->4->5
1번에서 catch에서 잡지 않는 에러가 나면 1->5


----------------------------------
*IO
try{

 1.연결
 2.교환

}catch(){

 예외처리

}finally{

 3.연결끊기

}

----------------------------------
try : 오류날 가능성이 있는 코드-->실행코드(정상)
catch : try 블럭에서 난 오류를 처리하는 코드
finally : try와 catch의 상황과 상관 없이 무조건 실행되야 하는 코드.->실행코드(정상)

* 가능
- try{}catch(){}finally{}
- try{}finally{}
- try{}catch{}

 

 

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

File I/O filter처리  (0) 2012.07.29
File I/O  (0) 2012.07.29
난수구하기 및 수학함수  (0) 2012.07.29
java 시간 날짜 처리  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
Posted by 조은성
,

* double d = Math.random(); //난수 발생 범위(0.0 <= x < 1.0)
* java.util.Random r = new Random();
Int i = r.nextInt();//인트의 범위까지 정수형을 리턴한다.
int i1 = r.nextInt(100);//0~(100-1)까지의 숫자를 랜덤적으로 리턴한다.

package random;

import java.util.Random;

public class RandomTest {

 public static void main(String[] args) {
  Random r = new Random();
  System.out.println(r.nextInt());//int 범위에있는 모든 수를 random하게
  System.out.println(r.nextBoolean());
  System.out.println(r.nextDouble());;
  System.out.println(r.nextLong());
  int i = r.nextInt();
  while(i>=0){
   i = r.nextInt();
  }
  System.out.println(i);
  i = r.nextInt(10);//0~9까지 리턴
  while(i!=10){
   i = r.nextInt(10);
  }
  System.out.println(i);
 }

}
--------------------------------
================================================================

* 2012-3-26
* Java.math.BigDecimal - double로 표현이 안되는 부동 소숫점 표현  -> 구문 :  new (BigDecimal("10.5");
            BigInteger - long으로 표현이 안되는 정수를 표현

* project : day23
  package : number
  class : BigDecimalTest


package number;

import java.math.BigDecimal;

public class BigDecimalTest {
 public static void main(String[] args) {
  System.out.println(2.00-1.11);
  BigDecimal d1 = new BigDecimal("2.0");
  BigDecimal d2 = new BigDecimal("1.10");
  // + : add(), - : substract(), / : divide(), * : multiply()
  BigDecimal result  = d1.subtract(d2);
  double d = result.doubleValue();
  System.out.println(result +" : "+ d);
  //1 : 나눌 수, 2 : scale - 소숫점 이하 몇자리 까지보여줄것인지, 3 : 소숫점 이하 처리방식
  result = d1.divide(d2,3,BigDecimal.ROUND_CEILING);//소수점 3자리까지 나타내라.
  System.out.println("나눈 결과 : "+result);
 }
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

File I/O  (0) 2012.07.29
예외처리(Exception), try catch finally  (0) 2012.07.29
java 시간 날짜 처리  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
boxing, unboxing, wrapperClass  (0) 2012.07.29
Posted by 조은성
,

* 시간, 날짜 처리
java.util.Date
java.util.Calendar

- GregorianCalendar

생성자 종류
GregorianCalendar()
GregorianCalendar(int y, m, d)
GregorianCalendar(int y, m, d, h, m)

.get(int year)

- 요일 (일요일(0)~토요일(6))

package calendar;

import java.util.*;
public class CalendarTest {
 public static void main(String[] args) {
  //현재 시간을 출력하는 프로그램을 만드세요.- Calendar, GregroianCalendar
  //Calendar c = Calendar.getInstance();    //아래 GregorianCalendar gc = new GregorianCalendar(); 이렇게 사용한 것과 같다.
//  GregorianCalendar gc = new GregorianCalendar();
//  TimeZone tz = TimeZone.getTimeZone("Europe/London");
//  gc.setTimeZone(tz);//영국시간대로 변경
  GregorianCalendar gc = new GregorianCalendar(2005,2, 20);

//  System.out.println(gc.isLeapYear(2012));  //윤년이 있는지 없는지를 알려줌.
  int year = gc.get(Calendar.YEAR);
  int month = gc.get(Calendar.MONTH)+1;
  int day = gc.get(Calendar.DATE);//Calendar.DAY_OF_MONTH
  String amPm = (gc.get(Calendar.AM_PM)==Calendar.AM) ? "오전":"오후";
  int hour = gc.get(Calendar.HOUR);//0~11, Calendar.HOUR_OF_DAY:0~23
  int minute = gc.get(Calendar.MINUTE);
  int second = gc.get(Calendar.SECOND);
  String dayOfWeek = null;
  switch(gc.get(Calendar.DAY_OF_WEEK)){
   case Calendar.SUNDAY:
    dayOfWeek = "일요일";
    break;
   case Calendar.MONDAY:
    dayOfWeek = "월요일";
    break;
   case Calendar.TUESDAY:
    dayOfWeek = "화요일";
    break;
   case Calendar.FRIDAY:
    dayOfWeek = "금요일";
    break;
   
  }
  //2011년 10월 4일 오전 11시 21분 23초 화요일
  System.out.println(year+"년 "+month+"월 "+day+"일 "+amPm+" "+hour+"시 "+minute+"분 "+second+"초 "+dayOfWeek);

 }
}


---------------
=======================================================

*세계시간 구하기(타임존 구하기)

package calendar;

import java.util.TimeZone;

public class PrintTimeZone {
 public static void main(String[] args) {
 String [] timeZone = TimeZone.getAvailableIDs();
  for(String tz : timeZone){
   System.out.println(tz);
  }
 }
}

----------
========================================================

* project : day23
package : calendar
class : CalendarTest2


package calendar;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

public class CalendarTest2 {
 public static void main(String[] args) {
  long l1 = System.currentTimeMillis(); //현재시간을 1/1000 초로 알려줌. 1970.1.1.0.0.0.0초 부터
  for(int i =0;i<1000;i++){
//   System.out.println(i);
  }
  System.out.println(l1);
  long l2 = System.currentTimeMillis();
  System.err.println(l2 - l1);
  GregorianCalendar gc = new GregorianCalendar();
  long miliS = gc.getTimeInMillis();
  System.out.println(miliS);
  
  System.out.println("-----------SimpleDateFormat을 이용--------------");
  SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd a HH : mm : ss E"); //a는 오전,오후 E는 요일
  //String str = sf.format(gc); //GregorianCalendar와 SimpleDateFormat은 상속관계가 아니라 넣을 수 없다.
  
  Date d = gc.getTime();//GregorianCalendar을 Date 타입으로 바꿔준다.
  String str = sf.format(d); //GregorianCalendar와 SimpleDateFormat은 상속관계가 아니라 넣을 수 없다.
  System.out.println(str);
 }
 
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

예외처리(Exception), try catch finally  (0) 2012.07.29
난수구하기 및 수학함수  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
boxing, unboxing, wrapperClass  (0) 2012.07.29
object클래스  (0) 2012.07.29
Posted by 조은성
,

* 문자열 관리해주는 class - String, StringBuffer(String에 가기 전 임시저장소), StringBuilder
                            ->char[]로 처리한다. -> length : 글자수
                                                 -> idx : 글자의 위치

String s = "Hello";
     idx가  01234
만약에 s.charAt(4);//o 가 나온다.

char c1 = 'H';
char c2 = 'e';
char c3 = 'l';
char c4 = 'l';
char c5 = 'o';

char[] c = {'H','e','l','l','o'};

* String - 한번 객체가 만들어 지면 그 값은 절대 불변.
ex:
String s = "abc";//String s = new String("abc"); //한번 abc 문자열이 들어가면 죽을 때 까지 abc를 가지고 있는 객체가 된다.
s.concat("def"); //abc def가 따로 객체가 2개가 생긴다.
system.out.println(s); //결과 : abc

->값 : " "
  객체 : String s = "abc";
  String s = new String("abc");


* project : day23
  package : string
  class : StringTest

package string;

public class StringTest {
 public static void main(String[] args) {
  String s1 = "abcde";
  String s2 = new String("abcde");
  String s3 = "ABCDE";
  //글자수를 조회하는 메소드
  int strLength = s1.length();
  System.out.println(strLength);
  //두 String의 내용값이 같은지 비교
  System.out.println("s1 == s2 : "+(s1 == s2));//주소값 비교  다른객체를 비교하니 결과 :  false
  System.out.println("s1.equals(s2) : "+s1.equals(s2));//내용값 비교      //내용이 같으니 결과 : true
  System.out.println("s1.equals(s3) : "+s1.equals(s3));                     //대소문자가 달라서 결과 : false
  System.out.println("s1.equalsIgnoreCase(s3) : "+s1.equalsIgnoreCase(s3));//대소문자 무시하고 내용값 비교  //대소문자를 무시하니 결과 : true
  //조회하는 메소드들
  //특정문자열로 시작/끝나는지 비교
  //시작
  boolean flag = s1.startsWith("ab");//ab로 시작하는지?
  System.out.println("s1.startsWith(\"ab\") : "+flag);
  System.out.println("s1.endsWith(\"ef\") : "+s1.endsWith("ef"));
  //특정 문자나 문자열이 몇번째 글자인지 조회
  String s4 = "abc abc abcdef";//a : 0, 4, 8
  int idx = s4.indexOf("a");        
  System.out.println("s4.indexOf(\"a\") : "+idx); //찾아서 a를 딱 찾으면 그 index만 리턴
  System.out.println("s4.indexOf(\" abc\") : "+s4.indexOf(" abc")); //공백 index는 3번에 있다
  //뒤에서부터 조회
  System.out.println("s4.lastIndexOf(\"a\") : "+s4.lastIndexOf("a"));//뒤에서 부터 a를 찾으면 8번이 된다.
  System.out.println("s4.lastIndexOf(\" abc\") : "+s4.lastIndexOf(" abc")); //뒤어서 부터 공백abc를 찾으면 7이 된다.
  System.out.println("s4.indexOf(\"a\", 2) : "+s4.indexOf("a", 2));//2번 index에서부터 찾기 시작
  //String 에서 특정 index의 문자를 조회
  char c = s4.charAt(5);//5번 index의 char를 return
  System.out.println("s4.charAt(5) : "+c);  //5번에 있는 문자를 리턴해서 b리턴
  //문자열 일부분을 조회
  String s5 = "안녕하세요. Hello. 반갑습니다.";
  //반 : 14 H : 7 , 12
  String ss = s5.substring(14);//14번 index 부터 끝까지
  System.out.println("s5.substring(14) : "+ss);//14번 index 부터 끝까지  결과 :  반갑습니다.
  System.out.println("s5.substring(7, 12) : "+s5.substring(7, 12));//7~12-1 결과 : Hello
  //변경 하는 메소드
  //대문자->소문자
  ss = s3.toLowerCase(); //객체가 따로 만들어 지므로 변수에 대입해야 한다. 결과 : abcde 문자열 전부 대문자로 바꾸기 ctrl + shift + x, 소문자로 바꾸기 ctrl + shift + y
  System.out.println(s3+","+ss);
  //소문자 -> 대문자
  ss = s1.toUpperCase();
  System.out.println(s1+","+ss);
  //특정 char를 다른 char로 변경
  String s6 = "ababaaabb";
  //'a' -> 'k'
  ss = s6.replace('a', 'k');
  System.out.println(s6+","+ss);
  //특정 문자열을 다른 문자열로 변경
  ss = s5.replaceAll("Hello", "헬로");
  System.out.println(s5+","+ss);
  String s7 = "사과.배.귤,포도,딸기,메론,바나나";
  //String [] fruit = s7.split("\\.");
  String [] fruit = s7.split(",");
  //String [] fruit = s7.split(" ");
  System.out.println("------split() : 과일들----");
  for(String str : fruit){
   System.out.println(str);
  }

 }
}
//StringTest.java

-----------
================================================================

* project : day23
  package : string
  class : GetExention


package string;

public class GetExtention {

 public static void main(String[] args) {
  // command line argument로 파일명.확장자를 받아서 확장자만 출력하는 로직 구현
  // abc.txt -> txt
  // System.out.println(args[0]);
  System.out.println(args[0]);
  if(args.length!=1){
   System.out.println("사용법 : java GetExtension");
   return ;
  }
  String fileName = args[0];
  
  int idx = args[0].lastIndexOf(".");
  if(idx !=-1){
  String str = args[0].substring(idx+1);
  System.out.println(str);

  }else{
   System.out.println("확장자가 없습니다.");
  }
 }

}


------------------------
===========================================================================


* StringBuffer --
                 |->문자열을 다루기(변경) 위한 class
  StringBuilder--
  (->String을 만들기위해서 만든것)

String s = "abc";
String s2 = s.concat("def");

StringBuffer sb = new StringBuffer("abc");
sb.append("def");

system.out.println(sb); //결과 : abcdef

* 문자열을 붙일때는 String을 사용하면 여러개의 객체가 생겨서 좋지 않고, 임시적으로 데이터를 저장하기 위해서는 StringBuffer가 좋다. (중간에 문자열을 바꿔나갈때는 StringBuffer가 좋다. 결과는 마지막에 String에 담아 주면 된다.)

* 처음에 StringBuffer나 StringBuilder에 크기를 정해 놓고 할 수 있다. 미리 정해 두고 하는게 속도 측면에서 좋다. new StringBuffer("초기 문자열");
* 초기 문자열을 넣어두고 시작할 수 있다. new StringBuffer(10); //초기 문자열을 넣어두고 넘치면 그 글자수가 늘어난다.

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

난수구하기 및 수학함수  (0) 2012.07.29
java 시간 날짜 처리  (0) 2012.07.29
boxing, unboxing, wrapperClass  (0) 2012.07.29
object클래스  (0) 2012.07.29
제너릭  (0) 2012.07.29
Posted by 조은성
,

* 프리미티브 타입

char - Character
int - Integer
long - Long
double - double
float - float
byte - Byte
short - short
boolean - Boolean

* boxing : primitive - > Wrapper객체화
생성자의 argument로 넣어 객체 생성.
ex:
   new Integer(10);
   new Integer("10");// 숫자로 받을 수 있는 문자열도 넣을 수 있다.
   new Long(l); //long, double, float... 다 마찬가지로 숫자와 문자열을 넣을 수 있다.

- unboxing :  Wrapper객체 -> primitive
       wrapper객체.xxxValue();//xxx에는 primitive type이 온다.

int i = in.intValue();
long l = ln.longValue();

jdk1.5버전 이상부터는 자동으로 일어난다.
- autoboxing
int i = 10;
Integer in = new Integer(i);
Integer in = i;
Long l = 10L;

 

- autounboxing
Integer in = new Integer(10);
int i = in.intValue();
int i = in;

*
project : day22
package : wrapper
class : WrapperTest


package wrapper;

import java.util.ArrayList;

public class WrapperTest {
 public static void boxingUnboxingTest(){
  //boxing : primitive -> 객체(Wrapper)
  int i=10;
  Integer in = new Integer(i);
  Boolean b = new Boolean(false);
  Long l = new Long("10");
  //unboxing : Wrapper 객체 -> primitive
  int j = in.intValue();
  boolean b2 = b.booleanValue();
  long l2 = l.longValue();
  System.out.println(in+" - "+j);
 }
 public static void autoBoxingUnboxing(){
  //auto boxing
  Integer in =10;
  Boolean b1 = true;
  
  //auto unboxing
  int i = in;
  boolean b = b1;
  
  ArrayList list = new ArrayList();
  list.add(20);//Integer객체
  list.add(50L);//Long 객체
  list.add(false);//Boolean 객체
  int j = (Integer)list.get(0);
  long l = (Long)list.get(1);
  boolean b2 = (Boolean)list.get(2);
  ArrayList<Integer> list2 = new ArrayList<Integer>();
  list2.add(10);
  list2.add(20);
  int k = list2.get(0);
  //향상된 for문으로 list 출력
  for(Object o : list){
   System.out.println(o);
  }
 }
 public static void StringToWrapper(){
  //문자열 값을 Wrapper 객체에 넣기.
  //Integer in = "10";
  Integer in = new Integer("10");
  int i = in;
  Boolean b1 = new Boolean("false");
  //Long l1 = new Long("abcde");//숫자형태가 아니기 떄문에 컴파일 시점에는 괜찮지만 실행시점에서 에러가 난다.
  //Long l1 = new Long("10abcde");
  Long l1 = new Long("10");
  //String -> primitive
  //WrapperClass.parseXXXX(xxxx); XXXX프리미티브
  int r = Integer.parseInt("20030");
  double d = Double.parseDouble("2030.12");
  boolean b = Boolean.parseBoolean("false");
  //float f = Float.parseFloat("abcde"); //숫자로 바꿀수 없기때문에 컴파일은 되도 실행시점에서 오류가 난다. 숫자로 바꿀수 있는 문자열을 넣어야 한다.
  //char c = Character.parseChar("a");//이런건 없다.
  char c = "a".charAt(0);
 }
 public static void main(String[] args) {
  boxingUnboxingTest();
  autoBoxingUnboxing();
  StringToWrapper();
 }
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

java 시간 날짜 처리  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
object클래스  (0) 2012.07.29
제너릭  (0) 2012.07.29
collection값 빼오기  (0) 2012.07.28
Posted by 조은성
,

* Object class
- java.lang.Object : 모든 class의 최상위->모든 객체의 type이 될 수 있다.

* Object class는 추상적이어서 여기 있는 메소드를 직접 사용하는게 중요한게 아니라 하위 클래스에서 오버라이딩 해서 사용하는 것이 중요하다.
* +toString() : String -> 객체(Object)를 String으로 변환
- 메서드 이름이 객체.toXXXX()로 되면
to -> 변환

ex :
ProductDTO p = new ProductDTO();
p.toString(); <- p객체를 String으로 바꿔라.
* class이름@16진수 "ProductDTO@a567.." 이런식으로 바꿔준다. @a567...은 hashCode(객체의 가상의주소)로 바꿔준다.
->Object 타입의 toString()은 사용하지 않는다. 중요한 것은 오버라이딩 해서 사용하는 것이 중요한 것이다.
->toString()을 오버라이딩 할 시에는 Attribute들을 문자열로 return해줌.
(대표적인 toString()오버라이드한 객체들 String, StringBuffer, WrapperClass, Collection)

*equals(obj : Object) : boolean
- 매개변수로 받은 객체가 같은 객체인지 비교
ex)  obj1.equals(obj2); -> obj1==obj2


- overriding : 두객체의 attribute의 값이 같다면 true 리턴

equals overriding
public boolean equals(Object obj){
 1. obj가 null인지
 2. obj가 같은지
 3. 속성값들이 같은지
}
- equals()메소드를 오버라이딩 할때 반드시 hashCode()메소드도 같이 overriding한다.
-> + int hashCode()도 오버로딩 해야함.

o1.equals(o2); ==> true 면
o1.hashCode() ==> attribute가 같으면 hashCode()도 같게 나오게 해야한다.
o2.hashCode() ==> 디 둘도 true가 나와야 같은 객체라 생각한다.

* 값을 비교할때 equals를 쓴다. 따라서 attribute가 같으면 같은 객체다. equals메소드가 true가 나오고 hashCode()값도 true가 나와야 같은 객체다.
(equals overriding하면 hashCode()도 오버라이딩 해라.

project : day22
package : object.method
class :  ProductDTO

 

package object.method;

public class ProductDTO {
 private String productId;
 private String productName;
 private int price;
 private String productMaker;
 
 //생성자
 public ProductDTO() {
 }
 public ProductDTO(String productId, String productName, int price,
   String productMaker) {
  this.productId = productId;
  this.productName = productName;
  this.price = price;
  this.productMaker = productMaker;
 }
 
 //getter/setter
 public String getProductId() {
  return productId;
 }
 public void setProductId(String productId) {
  this.productId = productId;
 }
 public String getProductName() {
  return productName;
 }
 public void setProductName(String productName) {
  this.productName = productName;
 }
 public int getPrice() {
  return price;
 }
 public void setPrice(int price) {
  this.price = price;
 }
 public String getProductMaker() {
  return productMaker;
 }
 public void setProductMaker(String productMaker) {
  this.productMaker = productMaker;
 }
 //toString()
 @Override
 public String toString() {
  return "ProductDTO [productId=" + productId + ", productName="
    + productName + ", price=" + price + ", productMaker="
    + productMaker + "]";
 }
 //equals(), hashCode()
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + price;
  result = prime * result
    + ((productId == null) ? 0 : productId.hashCode());
  result = prime * result
    + ((productMaker == null) ? 0 : productMaker.hashCode());
  result = prime * result
    + ((productName == null) ? 0 : productName.hashCode());
  return result;
 }
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  ProductDTO other = (ProductDTO) obj;
  if (price != other.price)
   return false;
  if (productId == null) {
   if (other.productId != null)
    return false;
  } else if (!productId.equals(other.productId))
   return false;
  if (productMaker == null) {
   if (other.productMaker != null)
    return false;
  } else if (!productMaker.equals(other.productMaker))
   return false;
  if (productName == null) {
   if (other.productName != null)
    return false;
  } else if (!productName.equals(other.productName))
   return false;
  return true;
 }
}


-----------------

package object.method;

import java.util.HashSet;

public class TestEquals {
 public static void main(String[] args) {
  ProductDTO pto1 = new ProductDTO("p-1","TV",2000,"LG");
  ProductDTO pto2 = new ProductDTO("p-1","TV",2000,"LG");
  System.out.println("pto1 == pto2 - >"+(pto1==pto2));//객체의 주소값 비교
  boolean flag = pto1.equals(pto2);
  System.out.println("pto1.equals(pto2) -> "+flag);
  HashSet set = new HashSet(); //중복허용 X
  set.add(pto1);
  set.add(pto2);
  System.out.println(set);//equals와 hashCode를 둘다 오버라이딩 해야 같은 객체로 판단한다.
 }
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

String class, String buffer  (0) 2012.07.29
boxing, unboxing, wrapperClass  (0) 2012.07.29
제너릭  (0) 2012.07.29
collection값 빼오기  (0) 2012.07.28
map실습  (0) 2012.07.28
Posted by 조은성
,

* 제너릭 -1.5 : class에 사용할 type - class 작성 X
                                    - 사용시점에 지정 - O


ex :

A<String> a = new A<String>();

class A<String>{
 public void go(String a){
 }
}


위처럼 하면 A<String> a = new A<String>();
a.go();<-를 하면 String 값을 넘기는 것 밖에 안된다.
* 제너릭을 사용하지 않으면 실행은 잘되는데 컴파일 시점에 문제가 생길 수 있다.
제너릭을 쓰는 이유 Object 타입으로 썼을 경우 다른 객체들이 들어오는 건 장점이기도 하지만, 형변환시 문제가 생길 수 있기에 사용한다.
(타입에 대한 불안정을 해결해 준다.)


Project : day22
package : generic
class :   GenericTest


package generic;
class BasicGeneric<E , K>{
 
 public void printInfo(E obj){
//  if(obj instanceof String){
//  String str = (String)obj;
//  }
  System.out.println(obj);
 }

 public void test(K k){
  
 }
}
public class GenericTest {
 public static void main(String[] args) {
  BasicGeneric<String,String> b = new BasicGeneric<String,String>();
  b.printInfo("abcde");
  //b.printInfo(new Integer(10));
  BasicGeneric<Integer,String> b2 = new BasicGeneric<Integer,String>();
  b2.printInfo(new Integer(10));
 // b2.printInfo("abcde");
  BasicGeneric b3 = new BasicGeneric();//BasicGeneric<Object> b2 = new BasicGeneric<Object>();
  b3.printInfo("abcde");
  b3.printInfo(new Integer(20));
 }
}

-----------------
=============================================


Project : day22
package : generic
class :   CollectionGeneric

package generic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class CollectionGeneric {
 public static void main(String[] args) {
  ArrayList<String> list = new ArrayList<String>();
  list.add("String1");
  list.add("String2");
  //list.add(new Integer(10));
  //list.add(new CollectionGeneric());
  String str = list.get(0);
  
  for(String o : list){
   System.out.println(o); 
  }
  //////////map//////////
  HashMap<String,Integer> map = new HashMap<String,Integer>();
  //map.put("name", "홍길동");
  map.put("age", 10);
  map.put("age", new Integer(20));
  Integer age = map.get("age");
  Set<String> keys = map.keySet();
  Iterator<String> itr = keys.iterator();
  while(itr.hasNext()){
   String key = itr.next();
   Integer value = map.get(key);
   System.out.println(key+"-"+value);
  }
 }
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

boxing, unboxing, wrapperClass  (0) 2012.07.29
object클래스  (0) 2012.07.29
collection값 빼오기  (0) 2012.07.28
map실습  (0) 2012.07.28
ArrayList실습  (0) 2012.07.28
Posted by 조은성
,

* 값 빼오는 패턴
1. 배열 - arr

for(int idx = 0;idx<arr.length;idx++)
{
 arr[idx];
}

2. List( ArrayList ) - list

for(int idx = 0; idx <list.size(); idx++){
 Object obj = list.get(idx); 
 
}

3. Set - set

Iterator itr = set.iterator();
while(itr.hasNext()){
 Object obj = itr.next();
}

1.5버전 이상일때는 향상된 for문도 된다
for(Object o : set){
 Object obj = o;
}

4. Map - map

Set keys = map.keySet();
Iterator itr = keys.iterator();
while(itr.hasNext()){
 Object key = itr.next();
 Object value = map.get(key);
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

object클래스  (0) 2012.07.29
제너릭  (0) 2012.07.29
map실습  (0) 2012.07.28
ArrayList실습  (0) 2012.07.28
5개의 로또번호 출력하기 - collection실습  (0) 2012.07.28
Posted by 조은성
,

* 전체적으로 조회하는 것은 List가 좋고, 키 값을 가지고 딱 하나만 찾아 낼때는 Map이 편하다.
* Map -* HashTable <- Properties(객체와 객체에서 문자열로 특화시킨 것) <- key(String)
                                    value(String)
      -* HashMap <- key(Object) : key값 안에 들어가는 타입은 거의 String이 들어간다.
      중복허용(X)
      같은 Key-Object추가
      replace처리.
                    value(Object) : 중복허용(O)
        순서개념 없다.
* Map -* key - value
        (Object) (Object)

         - key와 value를 합치면 entry라 부른다.

- 메소드

추가, 변경(replace) : put(Object key,Object value)
조회 : get(Object key) : Object(Value)
삭제 : remove(Object key) : Object(Value)
Key값들(전체)을 조회하는 메소드 : keySet() : Set
entry들(전체)을 조회하는 메소드 : entrySet() : Entry
전체데이터 삭제 : clear()
entry의 개수 : size() : int

* key값의 존재 유무 :  containsKey(Object key) : boolean
  Value값의 존재 유무 :  containsValue(Object value) : boolean

* Map은 테이블 형태로 들어간다.

key    value
-----------------
| k1   |   1    |->entry
|-------------
| k2   |   2    |
|---------------
 

* project : day19
  package : collection.map
  class : MapTest

*new버전 :  java.util.Iterator (Interface) - 조회와 삭제가 가능
 old버전 : (java.util.Enumeration) (Interface) -  조회만 가능
 ->Collection(Interface) 객체가 관리하는 값(객체)들을 조회.

* Iterator : 조회와 삭제를 해준다.(데이터를 모아놓은 List나 Map이 있으면 옆에 붙어서 데이터를 조회 삭제만 한다. 데이터를 직접 모으진 않는다.)
  (장점 :  List나 Map, Set 등의 방법을 Iterator를 통해서 조회해 올수 있다. Set은 조회 방법이 없는데 Iterator를 통해서는 가능하다.)
  -> 값을 순서적으로 돌면서 하나씩 넘겨준다. 값이 없으면 값을 넘기지 않는다.

- Iterator메소드
가져올 값(return할 값)이 있는지 유무 :  hasNext() : boolean
값 리턴 : next() : Object
값 삭제 : remove() : void

- Enumeration
가져올 값(return할 값)이 있는지 유무 :  hasMoreElements() : boolean
값 리턴 : nextElement() : Object

* 사용법

Collection객체.iterator() -> Iterator
Collection객체 = Set,List..


* iterator를 사용한 조회
ex :
  System.out.println("----------Iterator를 이용한 조회-----------------");
  
  Iterator itr = set.iterator();
//  System.out.println(itr.next());
//  System.out.println(itr.next());
//  System.out.println(itr.next());
//  System.out.println(itr.next());
//  System.out.println(itr.next());
  
  while(itr.hasNext()){
   Object obj = itr.next();
   System.out.println(obj);
  }

-------------------------------------------------------------------------------

* Map을 사용한 상품관리 소스

package product.test;
import java.util.ArrayList;
import java.util.List;

import product.dto.DVDPlayer;
import product.dto.ProductDTO;
import product.dto.Television;
import product.service.ProductManagerService;
import product.service.ProductManagerServiceMap;

public class TestProductManagerMap{
 public static void main(String[] args){
  Television tv1 = new Television("tv-111", "LG-3D TV", 2000000, "LG", "최신형 티비", true, true, true);
  Television tv2 = new Television("tv-222", "파브-TV", 1000000, "삼성", "LCD 티비", false, false, true);
//  Television tv2 = new Television("tv-111", "파브-TV", 1000000, "삼성", "LCD 티비", false, false, true);
  DVDPlayer dvd1 = new DVDPlayer("dvd-111", "Bluelay-one", 120000, "삼성", "최신형 블루레이 플레이어", "C", true);
  DVDPlayer dvd2 = new DVDPlayer("dvd-222", "dvd-one", 50000, "LG", "DVD-RW 플레이어", "C", false);
  //관리자인 ProductManagerService객체 생성
  ProductManagerServiceMap pm = new ProductManagerServiceMap();
  pm.addProduct(tv1);
  pm.addProduct(tv2);
  pm.addProduct(dvd1); 
  pm.addProduct(dvd2);
  System.out.println("-------------상품 추가후---------------");
  pm.printProductList();//productList에 저장된 모든 ProductDTO 정보를 프린트
  System.out.println("-----------id로 제품정보 조회------------");
  ProductDTO p1 = pm.searchProductById("tv-111");
  System.out.println("tv-111 제품 정보 : "+p1);
  ProductDTO p2 = pm.searchProductById("tv-222");
  System.out.println("tv-222 제품 정보 : "+p2);
  ProductDTO p3 = pm.searchProductById("dvd-111");
  System.out.println("dvd-111 제품 정보 : "+p3);
  //없는 ID로 조회
  ProductDTO p4 = pm.searchProductById("dvd-222");
  System.out.println("dvd-222 제품 정보 : "+p4);
  System.out.println("-----------정보수정--------------");
  dvd2 = new DVDPlayer("dvd-222", "dvd-one", 702010, "LG", "DVD-RW 플레이어", "Code free", true);
  pm.modifyProductInfo(dvd2);
  pm.printProductList();
  System.out.println("--------삭제----------");
  pm.removeProductById("tv-111");
  pm.printProductList();
  System.out.println("--------Maker조회----------");
  
  ArrayList list = pm.searchProductsByMaker("삼성");
  
  for(int i=0;i<list.size();i++){
   System.out.println(list.get(i));
  }
  
  System.out.println("--------remove조회(Maker로 조회해서 온것 다 삭제----------");
  
 
  for(Object o : list){
   ProductDTO p = (ProductDTO)o;
   pm.removeProductById(p.getProductId());
  }
  pm.printProductList();
 }
}
---------------------------------

package product.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

 

import product.dto.ProductDTO;

public class ProductManagerServiceMap {
 private HashMap productList;

 // private ArrayList productList = new ArrayList();

 // 생성자
 public ProductManagerServiceMap() {
  productList = new HashMap();
 }

 private boolean isNull(Object obj) {
  // boolean flag = false;
  // if(obj ==null){
  // flag =true;
  // }
  // return flag;
  return obj == null;
 }

 // productList에 저장된 모든 제품 정보 출력
 public void printProductList() {

  Set key = productList.keySet();
  Iterator itr = key.iterator();
  while(itr.hasNext()){
//   Object key1 = itr.next();
//   ProductDTO value1 = (ProductDTO) productList.get(key1);
//   System.out.println(value1);
   System.out.println((ProductDTO) productList.get(itr.next()));
   
  }
//  for (Object obj : productList) {
//   System.out.println(obj);
//  }
 }

 // 추가
 public void addProduct(ProductDTO pdto) {
  if (isNull(pdto)) {
   System.out.println("Null 데이터는 추가할 수 없습니다.");
   return;
  }

  /*
   * //같은 ID가 있는지 비교. for(int i=0;i<productList.size();i++){ // ProductDTO
   * pto = (ProductDTO)productList.get(i); //
   * if(pdto.getProductId().equals(pto.getProductId())){ // // }
   * if(((ProductDTO)
   * productList.get(i)).getProductId().equals(pdto.getProductId())){
   * System.out.println("이미 등록된 제품 ID입니다. ID를 바꿔주세요."); return; } }
   */
  if(productList.containsKey(pdto.getProductId())){
   System.out.println("동일한 아이디가 있습니다.");
   return;
  }
  productList.put(pdto.getProductId(), pdto);
 }

 // id로 제품을 조회해서 return
 public ProductDTO searchProductById(String productId) {

  return (ProductDTO) productList.get(productId);

 }

 public void modifyProductInfo(ProductDTO pdto) {
  if (isNull(pdto)) {
   System.out.println("인자로 null값이 들어 왔습니다.");
   return;
  }
  if(!productList.containsKey(pdto.getProductId())){
   System.out.println("동일한 Id가 없습니다.");
   return;
  }
  productList.put(pdto.getProductId(), pdto);

 }

 public void removeProductById(String productId) {

  if (isNull(productId)) {
   System.out.println("인자로 null값이 들어 왔습니다.");
   return;
  }
  if(!productList.containsKey(productId)){
   System.out.println("동일한 아이디가 없습니다.");
   return;
  }
  productList.remove(productId);
  
 }
 public ArrayList searchProductsByMaker(String productsMaker){
  ArrayList list = new ArrayList();
  

  Set keys = productList.keySet();
  Iterator itr = keys.iterator();
  while(itr.hasNext()){
   Object id = itr.next();
   ProductDTO pto = (ProductDTO) productList.get(id);
   if(productsMaker.equals(pto.getProductMaker())){
    list.add(pto);
   }
  }
  return list;
  
 }
}


---------------------------------

package product.dto;

public class ProductDTO {
 private String productId;
 private String productName;
 private int productPrice;
 private String productMaker;
 private String productInfo;
 public ProductDTO(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  this.productId = productId;
  this.productName = productName;
  this.productPrice = productPrice;
  this.productMaker = productMaker;
  this.productInfo = productInfo;
 }
 public ProductDTO() {
 }
 public String getProductId() {
  return productId;
 }
 public void setProductId(String productId) {
  this.productId = productId;
 }
 public String getProductName() {
  return productName;
 }
 public void setProductName(String productName) {
  this.productName = productName;
 }
 public int getProductPrice() {
  return productPrice;
 }
 public void setProductPrice(int productPrice) {
  this.productPrice = productPrice;
 }
 public String getProductMaker() {
  return productMaker;
 }
 public void setProductMaker(String productMaker) {
  this.productMaker = productMaker;
 }
 public String getProductInfo() {
  return productInfo;
 }
 public void setProductInfo(String productInfo) {
  this.productInfo = productInfo;
 }
 @Override
 public String toString() {
  return "ProductDTO [productId=" + productId + ", productName="
    + productName + ", productPrice=" + productPrice
    + ", productMaker=" + productMaker + ", productInfo="
    + productInfo + "]";
 }
 
}


-----------------------

package product.dto;

public class Television extends ProductDTO{
 private boolean threeD;
 private boolean smartTV;
 private boolean usb;
 public Television(String productId, String productName, int productPrice,
   String productMaker, String productInfo, boolean threeD,
   boolean smartTV, boolean usb) {
  super(productId, productName, productPrice, productMaker, productInfo);
  this.threeD = threeD;
  this.smartTV = smartTV;
  this.usb = usb;
 }
 public Television(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  super(productId, productName, productPrice, productMaker, productInfo);
 }
 public boolean isThreeD() {
  return threeD;
 }
 public void setThreeD(boolean threeD) {
  this.threeD = threeD;
 }
 public boolean isSmartTV() {
  return smartTV;
 }
 public void setSmartTV(boolean smartTV) {
  this.smartTV = smartTV;
 }
 public boolean isUsb() {
  return usb;
 }
 public void setUsb(boolean usb) {
  this.usb = usb;
 }
 @Override
 public String toString() {
  return "Television [threeD=" + (threeD ? "3DTV" : "2GTV") + ", smartTV=" + (smartTV ? "스마트TV" : "일반TV")
    + ", usb=" + (usb ? "Usb사용가능" : "usb사용불가능") + ", 일반제품정보=" + super.toString() + "]";
 }

 

 
 
}


------------------------

package product.dto;

public class DVDPlayer extends ProductDTO{
 private String areaCode;
 private boolean bluelay;
 public DVDPlayer(String productId, String productName, int productPrice,
   String productMaker, String productInfo, String areaCode,
   boolean bluelay) {
  super(productId, productName, productPrice, productMaker, productInfo);
  this.areaCode = areaCode;
  this.bluelay = bluelay;
 }
 public DVDPlayer(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  super(productId, productName, productPrice, productMaker, productInfo);
 }
 public String getAreaCode() {
  return areaCode;
 }
 public void setAreaCode(String areaCode) {
  this.areaCode = areaCode;
 }
 public boolean isBluelay() {
  return bluelay;
 }
 public void setBluelay(boolean bluelay) {
  this.bluelay = bluelay;
 }
 @Override
 public String toString() {
  return "DVDPlayer [areaCode=" + areaCode + ", bluelay=" + (bluelay? "사용가능" : "사용불가능")
    + ", 일반제품정보=" + super.toString() + "]";
 }

 

}


----------------------


* map 타입 맞추기
HashMap map = new HashMap();
map.put("name","홍길동");
map.put("age",10);

Set ke = map.keySet();
Iterator itr = ke.iterator();
while(itr.hasNext()){
String k = (String)itr.next();
String v = (String)map.get(k);  //이렇게 하면 age의 10인 Integer를 받아올 때 실행시점에 에러가 난다.

그래서 제너릭을 사용해서 map만들 시에 타입을 HashMap<String, String> map = new HashMap(); 이렇게 해서 String 타입만 넣을 수 있게 한다.
제너릭은 실행 시점에 지정한다.

* Generic(제너릭) : class에서 사용할 type을 class작성시 지정하는 것이 아니라 사용시점에 지정하는 것.
구문 :  class선언
public class ClassName<E>{
public void go(E e){
}

사용
ClassName<String> c1 = new ClassNAme<String>();
ClassName<Human> c2 = new ClassName<Human>();

c1.go(String s);//(O)
c1.go(Integer i);//(X)


* Generic파라미터는 static 멤버에서는 사용 불가능 하다.

ArrayList<String> list = new ArrayList<String>();
list.add("aaa");
String str = list.get(0);
//list.add(new Human());//(X)

* 2012-3-22

* Enumeration enu;

while(enu.hasMoreElements()){
Object obj = enu.nextElement();
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

제너릭  (0) 2012.07.29
collection값 빼오기  (0) 2012.07.28
ArrayList실습  (0) 2012.07.28
5개의 로또번호 출력하기 - collection실습  (0) 2012.07.28
컬렉션(collection)  (0) 2012.07.28
Posted by 조은성
,

* ArrayList - 불안전한 대신에 퍼포먼스가 빠르다.(안전한 상황을 만들 수 있다.)
* Vector - 안전한 대신에 퍼포먼스가 느리다.
* Set - 순서허용X      추가 :  add(추가할 객체)
 중복허용X      삭제 : remove(삭제할 객체) : Object
* List- 순서허용       크기 : size()
 중복허용       조회 : set : X
                              List : get(index)
* Map - HashMap
      - HashTable <- Properties(어떤 설정을 저장할 때 사용)

* ProductManagerArrayList
  Package : product.dto ->DTO 클래스
       product.service -> ProductManagerService
     product.test -> ProductTest
  class :

1. DTO(tel, dvd)
2. ProductManagerService - Attribute,Product(),생성자, printProductList()

ex :
//TestProductManager.java


package product.test;
import java.util.ArrayList;
import java.util.List;

import product.dto.DVDPlayer;
import product.dto.ProductDTO;
import product.dto.Television;
import product.service.ProductManagerService;

public class TestProductManager{
 public static void main(String[] args){
  Television tv1 = new Television("tv-111", "LG-3D TV", 2000000, "LG", "최신형 티비", true, true, true);
  Television tv2 = new Television("tv-222", "파브-TV", 1000000, "삼성", "LCD 티비", false, false, true);
//  Television tv2 = new Television("tv-111", "파브-TV", 1000000, "삼성", "LCD 티비", false, false, true);
  DVDPlayer dvd1 = new DVDPlayer("dvd-111", "Bluelay-one", 120000, "삼성", "최신형 블루레이 플레이어", "C", true);
  DVDPlayer dvd2 = new DVDPlayer("dvd-222", "dvd-one", 50000, "LG", "DVD-RW 플레이어", "C", false);
  //관리자인 ProductManagerService객체 생성
  ProductManagerService pm = new ProductManagerService();
  pm.addProduct(tv1);
  pm.addProduct(tv2);
  pm.addProduct(dvd1); 
  pm.addProduct(dvd2);
  System.out.println("-------------상품 추가후---------------");
  pm.printProductList();//productList에 저장된 모든 ProductDTO 정보를 프린트
  System.out.println("-----------id로 제품정보 조회------------");
  ProductDTO p1 = pm.searchProductById("tv-111");
  System.out.println("tv-111 제품 정보 : "+p1);
  ProductDTO p2 = pm.searchProductById("tv-222");
  System.out.println("tv-222 제품 정보 : "+p2);
  ProductDTO p3 = pm.searchProductById("dvd-111");
  System.out.println("dvd-111 제품 정보 : "+p3);
  //없는 ID로 조회
  ProductDTO p4 = pm.searchProductById("dvd-222");
  System.out.println("dvd-222 제품 정보 : "+p4);
  System.out.println("-----------정보수정--------------");
  dvd2 = new DVDPlayer("dvd-222", "dvd-one", 70000, "LG", "DVD-RW 플레이어", "Code free", true);
  pm.modifyProductInfo(dvd2);
  pm.printProductList();
  System.out.println("--------삭제----------");
  pm.removeProductById("tv-111");
  pm.printProductList();
  System.out.println("--------Maker조회----------");
  
  ArrayList list = pm.searchProductsByMaker("삼성");
  
  for(int i=0;i<list.size();i++){
   System.out.println(list.get(i));
  }
  
  System.out.println("--------remove조회----------");
  
 
  for(Object o : list){
   ProductDTO p = (ProductDTO)o;
   pm.removeProductById(p.getProductId());
  }
  pm.printProductList();
 }
}
-------------------------

package product.service;

import java.util.ArrayList;

import product.dto.ProductDTO;

public class ProductManagerService {
 private ArrayList productList;

 // private ArrayList productList = new ArrayList();

 // 생성자
 public ProductManagerService() {
  productList = new ArrayList();
 }

 private boolean isNull(Object obj) {
  // boolean flag = false;
  // if(obj ==null){
  // flag =true;
  // }
  // return flag;
  return obj == null;
 }

 // productList에 저장된 모든 제품 정보 출력
 public void printProductList() {
  // for(int i=0;i<productList.size();i++){
  // System.out.println(productList.get(i));
  // }
  for (Object obj : productList) {
   System.out.println(obj);
  }
 }

 // 추가
 public void addProduct(ProductDTO pdto) {
  if (isNull(pdto)) {
   System.out.println("Null 데이터는 추가할 수 없습니다.");
   return;
  }

  ProductDTO pt = searchProductById(pdto.getProductId());
  if (!isNull(pt)) {
   System.out.println("이미 등록된 제품 ID입니다. ID를 바꿔주세요.");
   return;
  }
  /*
   * //같은 ID가 있는지 비교. for(int i=0;i<productList.size();i++){ // ProductDTO
   * pto = (ProductDTO)productList.get(i); //
   * if(pdto.getProductId().equals(pto.getProductId())){ // // }
   * if(((ProductDTO)
   * productList.get(i)).getProductId().equals(pdto.getProductId())){
   * System.out.println("이미 등록된 제품 ID입니다. ID를 바꿔주세요."); return; } }
   */

  productList.add(pdto);
 }

 // id로 제품을 조회해서 return
 public ProductDTO searchProductById(String productId) {

  ProductDTO pDTO = null;
  if (isNull(productId)) {
   System.out.println("인자로 null값이 들어 왔습니다.");
   return pDTO;
  }

  for (int i = 0; i < productList.size(); i++) {
   if ((((ProductDTO) productList.get(i)).getProductId())
     .equals(productId)) {
    pDTO = ((ProductDTO) productList.get(i));
    break;
   }
  }
  return pDTO;

 }

 public void modifyProductInfo(ProductDTO pdto) {
  if (isNull(pdto)) {
   System.out.println("인자로 null값이 들어 왔습니다.");
   return;
  }
  for (int i = 0; i < productList.size(); i++) {
   if ((((ProductDTO) productList.get(i)).getProductId()).equals(pdto
     .getProductId())) {
    productList.set(i, pdto);
    break;
   }
  }
 }

 public void removeProductById(String productId) {

  if (isNull(productId)) {
   System.out.println("인자로 null값이 들어 왔습니다.");
   return;
  }
/*  for (int i = 0; i < productList.size(); i++) {
   if ((((ProductDTO) productList.get(i)).getProductId())
     .equals(productId)) {
    //productList.remove(i);
    
    // productList.remove(productId);//객체를 전부 지워야하는데 이름만 넘겨서 이름만 지우는 역할을 한다.
   }

  }*/
  ProductDTO pto = searchProductById(productId);
  productList.remove(pto);
 }
 public ArrayList searchProductsByMaker(String productsMaker){
  ArrayList productMakers = new ArrayList();
  for(int i=0;i<productList.size();i++){
   if((((ProductDTO) productList.get(i)).getProductMaker()).equals(productsMaker)){
    productMakers.add(productList.get(i));
   }
  }
  return productMakers;
  
 }
}


--------------------

package product.dto;

public class ProductDTO {
 private String productId;
 private String productName;
 private int productPrice;
 private String productMaker;
 private String productInfo;
 public ProductDTO(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  this.productId = productId;
  this.productName = productName;
  this.productPrice = productPrice;
  this.productMaker = productMaker;
  this.productInfo = productInfo;
 }
 public ProductDTO() {
 }
 public String getProductId() {
  return productId;
 }
 public void setProductId(String productId) {
  this.productId = productId;
 }
 public String getProductName() {
  return productName;
 }
 public void setProductName(String productName) {
  this.productName = productName;
 }
 public int getProductPrice() {
  return productPrice;
 }
 public void setProductPrice(int productPrice) {
  this.productPrice = productPrice;
 }
 public String getProductMaker() {
  return productMaker;
 }
 public void setProductMaker(String productMaker) {
  this.productMaker = productMaker;
 }
 public String getProductInfo() {
  return productInfo;
 }
 public void setProductInfo(String productInfo) {
  this.productInfo = productInfo;
 }
 @Override
 public String toString() {
  return "ProductDTO [productId=" + productId + ", productName="
    + productName + ", productPrice=" + productPrice
    + ", productMaker=" + productMaker + ", productInfo="
    + productInfo + "]";
 }
 
}


-----------------


package product.dto;

public class Television extends ProductDTO{
 private boolean threeD;
 private boolean smartTV;
 private boolean usb;
 public Television(String productId, String productName, int productPrice,
   String productMaker, String productInfo, boolean threeD,
   boolean smartTV, boolean usb) {
  super(productId, productName, productPrice, productMaker, productInfo);
  this.threeD = threeD;
  this.smartTV = smartTV;
  this.usb = usb;
 }
 public Television(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  super(productId, productName, productPrice, productMaker, productInfo);
 }
 public boolean isThreeD() {
  return threeD;
 }
 public void setThreeD(boolean threeD) {
  this.threeD = threeD;
 }
 public boolean isSmartTV() {
  return smartTV;
 }
 public void setSmartTV(boolean smartTV) {
  this.smartTV = smartTV;
 }
 public boolean isUsb() {
  return usb;
 }
 public void setUsb(boolean usb) {
  this.usb = usb;
 }
 @Override
 public String toString() {
  return "Television [threeD=" + (threeD ? "3DTV" : "2GTV") + ", smartTV=" + (smartTV ? "스마트TV" : "일반TV")
    + ", usb=" + (usb ? "Usb사용가능" : "usb사용불가능") + ", 일반제품정보=" + super.toString() + "]";
 }

 

 
 
}


---------------------

package product.dto;

public class DVDPlayer extends ProductDTO{
 private String areaCode;
 private boolean bluelay;
 public DVDPlayer(String productId, String productName, int productPrice,
   String productMaker, String productInfo, String areaCode,
   boolean bluelay) {
  super(productId, productName, productPrice, productMaker, productInfo);
  this.areaCode = areaCode;
  this.bluelay = bluelay;
 }
 public DVDPlayer(String productId, String productName, int productPrice,
   String productMaker, String productInfo) {
  super(productId, productName, productPrice, productMaker, productInfo);
 }
 public String getAreaCode() {
  return areaCode;
 }
 public void setAreaCode(String areaCode) {
  this.areaCode = areaCode;
 }
 public boolean isBluelay() {
  return bluelay;
 }
 public void setBluelay(boolean bluelay) {
  this.bluelay = bluelay;
 }
 @Override
 public String toString() {
  return "DVDPlayer [areaCode=" + areaCode + ", bluelay=" + (bluelay? "사용가능" : "사용불가능")
    + ", 일반제품정보=" + super.toString() + "]";
 }

 

}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

collection값 빼오기  (0) 2012.07.28
map실습  (0) 2012.07.28
5개의 로또번호 출력하기 - collection실습  (0) 2012.07.28
컬렉션(collection)  (0) 2012.07.28
인터페이스(interface)  (0) 2012.07.28
Posted by 조은성
,