* 프리미티브 타입

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 조은성
,