ABOUT ME

다시 시작~!

Today
Yesterday
Total
  • 10. 가장 자주 사용하는 JAVA.LANG 패키지.
    Programming/JAVA 2010. 5. 3. 21:09

    1. Object 클래스
    1.1개요

    디폴트 상속

    모든 클래스는 Object 클래스를 묵시적(디폴트)으 로 상속한다.

    자바에서 자동으로 수행되는 작업

    'import java.lang.*'을 하지 않아도 자동으로 import된다.

    또한, 'extends Object'를 사용하지 않아도 자동 으로 상속된다.

    생성자를 따로 지정하지 않은 경우 default 생성 자를 추가한다.
    1.1개요

    Object 클래스가 중요한 이유

    모든 클래스의 최상위 클래스

    참조값에 연결된 메모리와 직접적인 관련이 있는 메서드들로 이루어져 있기 때문
    1.1 개요

    Object 클래스의 멤버 메서드

    boolean equals(Object obj)

    String toString()

    int hashCode()

    protected void finalize()

    protected Object clone()

    final void notify(), final void notifyAll()

    final void wait(), final void wait(long timeout), final void wait(long timeout, int nanos)

    final Class getClass()

    final 멤버 메서드

    메서드에 final이 사용되면 더 이상 재정의가 불가능하도록 만든 다.

    그리고 클래스에 final이 사용되면 상속이 불가능하도록 만든다.

    변수에 사용되면 값의 변경이 안되는 상수가 된다.
    1.2 디폴트 toString()

    기본적인 기능

    객체의 클래스명 + “@” + 객체의 주소 값(16진수)

    객체 변수의 출력과 toString()의 문자열 출력은 동일 한 결과를 가진다.

    Top t = new Top();

    System.out.println(t);

    System.out.println(t.toString());

    결과

    Top@XXXXXX

    Top@XXXXXX

    동일한 결과임에 주목할 것!
    1.2 디폴트 toString()

    디폴트 toString()을 테스트하는 예제
    class Toy extends Object{
    //내용없음
    }
    public class ToStringMain{
    public static void main(String[] args){
    Toy t = new Toy();
    System.out.println(t);
    System.out.println(t.toString());
    }
    }
    1.3 toString() 오버라이딩

    toString()의 재정의를 테스트하는 예제
    class EBook {
    private int id;
    private String name;
    public EBook(int id, String name) {
    this.id = id;
    this.name = name;
    }
    public String toString() { //toString() 재정의
    return name + " " + id;
    }
    }
    public class ToStringMain2 {
    public static void main(String[] args) {
    EBook e1 = new EBook(1000, "노인과바다");
    EBook e2 = new EBook(2000, "이방인");
    System.out.println("e1: " + e1); //객체변수의출력
    System.out.println("e2: " + e2); //객체변수의출력
    }
    }
    1.3 toString() 오버라이딩

    toString()의 목적

    재정의를 목적으로 하며 사용자가 재정의해서 더중요하다 고생각되는정보를 문자열로 리턴한다.

    즉, 객체의요약정보를 문자열로 리턴하는 목적으로 사용 한다.
    1.4 미리 오버라이딩된 toString()

    toString()이 재정의되어 있는 Date 클래스

    Date d = new Date();

    System.out.println(d);

    System.out.println(d.toString());

    미리 재정의된 Date의 toString()
    import java.util.Date;
    public class DateMain{
    public static void main(String[] args) {
    System.out.println(new Date());
    System.out.println(new Date().toString());
    }
    }
    1.5 디폴트 equals()

    Object클래스의 equals() 메서드는 == 연산자와 동 일한 기능을 한다.

    class Apple{

    //...클래스의 내용

    }

    Apple a1 = new Apple();

    Apple a2 = new Apple();

    a1 == a2; //결과는 false(참조값 비교)

    a1.equals(a2); //결과는 false
    1.5 디폴트 equals()

    == 연산자를 사용하면 되는데 왜 굳이 equals() 메서드 를두고있는가?

    equals()의 목적

    디폴트 equals()는 참조값 비교이다.

    사용자가 재정의해서 사용자만의 비교법을 만들어서 사용할 목 적으로 제공되는 메서드

    재정의해서 사용자 정의 비교용 메서드로 사용한다.
    1.6 equals() 오버라이딩

    예제
    class GameUnit{
    private int id;
    private String name;
    public GameUnit(int id, String name) {
    this.id = id;
    this.name = name;
    }
    public int getId() {
    return this.id;
    }
    public String getName() {
    return this.name;
    }
    public boolean equals(Object obj) {
    if(obj instanceof GameUnit) {
    GameUnit eo =(GameUnit)obj;
    return (this.id == eo.id);
    }
    return false;
    }
    public String toString() {
    return id + ":" + name;
    }
    }
    멤버 변수 int id를 비교법으로 사용한다.
    1.6 equals() 오버라이딩

    예제 - 테스트
    class GmaeUnitTest{
    public static void main(String[] args){
    GameUnit e1 = new GameUnit(1000, "Tank");
    GameUnit e2 = new GameUnit(1000, "Missile" );
    System.out.println("e1: " + e1);
    System.out.println("e2: " + e2);
    System.out.println("e1.hashCode(): " + e1.hashCode());
    System.out.println("e2.hashCode(): " + e2.hashCode());
    System.out.println("e1==e2: "+(e1==e2));
    System.out.println("e1.eqauls(e2): "+ e1.equals(e2));
    }
    }
    1.7 미리 오버라이딩된 equals()

    String의 equals()

    String s1 = new String("Hello World");

    String s2 = new String("Hello World");

    s1 == s2; //결과는 false가 된다. - 참조값 비교

    s1.equals(s2); //결과는 true가 된다. - 문자열 비교
    1.7 미리 오버라이딩된 equals()

    equals()가 재정의된 대표적인 클래스

    String 객체

    객체 내의 문자열이 같으면 참

    Wrapper 객체

    Integer, Long, Float, Double, Character, Boolean 등의 각 Wrapper 객체가 가지고 있는 기본적인 데이터 형의 값이 같 으면 참

    Date 객체

    같은 날짜와 시간을 나타내고 있으면 참

    File 객체

    같은 경로명(PATH)를 표현하고 있으면 참
    1.8 hashCode()

    toString()의 원형
    public String toString(){
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

    객체의 고유 번호

    가상머신 내부에서 객체를 생성할 때 사용자를 위해 객체의 고유번호 는 동적으로 부여되며 사용자가 객체를 구별하는 기준이 된다.

    해시코드를 얻는 방법
    class HashMan{
    //...클래스의내용
    }
    HashMan h = new HashMan();
    int id = h.hashCode();

    객체의 해시코드(Hash Code)란?

    객체를 구별하기 위한 고유 번호
    2 finalize()
    2.1 finalize()

    protected void finalize()

    객체의 메모리가 제거되기 직전에 가비지 콜렉터에 의해서 자동으로 호출되는 메서드

    finalize()의 재정의


    class FinalMan extends Object{
    protected void finalize() throws Throwable {
    //작업
    super.finalize();
    }
    }
    2.2 finalize()의 구현
    class FinalMan{
    private FileWriter fw = null;
    public FinalMan(String filename) throws IOException{
    this.fw = new FileWriter(filename);
    }
    public void writeData(String str) throws IOException{
    this.fw.write(str);
    this.fw.flush();
    }
    protected void finalize() throws Throwable, IOException{
    if (this.fw != null){
    this.fw.close();
    }
    System.out.println("finalize()의파일닫기");
    super.finalize();
    }
    }
    2.2 finalize()의 구현
    public class FinalManMain{
    public static void main(String[] args) throws Exception{
    System.out.println("프로그램시작");
    //단순블록
    {
    FinalMan fm = new FinalMan("finalize.dat");
    fm.writeData("안녕하세요");
    fm.writeData("Hello");
    fm = null;
    }
    System.gc();//가비지콜렉터구동
    System.out.println("프로그램종료");
    }
    }
    3 clone()
    3.1 clone()

    메모리 차원의 복사

    오직 Object의 clone()만이 메모리 차원의 복사가 가능

    clone()의 사용

    protected이기 때문에 상속해서 Object 클래스의 clone()을 사용할 수 있다.

    Cloneable 인터페이스를 구현된 클래스에서 clone()을 사 용(호출)할 수 있다.

    메모리 복사를 위한 구현
    class Mimic implements Cloneable{
    public Object copyObject() throws CloneNotSupportedException{
    return super.clone();
    }
    }
    3.1 clone()

    객체복사를 위한 프로그램의 구현 순서

    Cloneable 인터페이스 구현

    새로운 메서드를 만든 후 super.clone() 호출

    메모리 복사를 위한 일반적인 clone()의 구현
    class Mimic extends Object implements Cloneable{
    public Object clone() throws CloneNotSupportedException{
    return super.clone();
    }
    }
    3.2 clone()의 구현
    class Mimic extends Object implements Cloneable{//Cloneable 명시
    private int id;
    private String name;
    public Mimic(int id, String name){
    this.id = id;
    this.name = name;
    }
    //clone() 메서드의재정의
    public Object clone() throws CloneNotSupportedException{
    return super.clone(); //Object의clone()을이용한메모리복제
    }
    //toString() 메서드의재정의
    public String toString(){
    return this.id + ":" + this.name;
    }
    }
    public class MimicMain{
    public static void main(String[] args) throws CloneNotSupportedException{
    Mimic m = new Mimic(1000, "호랑이"); //객체생성
    Mimic n = (Mimic)m.clone(); //복사를위한메서드사용
    System.out.println(m.hashCode() + " " + m); //객체의고유번호출력
    System.out.println(n.hashCode() + " " + n); //객체의고유번호출력
    }
    }
    3.3 복사

    예제
    import java.util.Vector;
    public class ShallowCloneMain {
    public static void main(String[] args){
    Vector v = new Vector();
    v.addElement(new String("Hello World"));
    v.addElement(new String("원본의글"));
    Vector s = (Vector)v.clone();
    System.out.println(v.elementAt(0) == s.elementAt(0));
    System.out.println(v.elementAt(1) == s.elementAt(1));
    }
    }
    4 wait()와 notify()
    4.1 wait()와 notify()

    wait()

    스레드를 NotRunnable상태로 만든다

    nofify(), notifyAll()

    스레드를 Runnable상태로 만든다.

    스레드를 NotRunnable로 만드는 두가지 방법이 있다.

    sleep()

    주어진 시간만큼 NotRunnable이 되며 시간이 지나면 자동적으 로 Runnable상태로 돌아온다

    wait()

    wait()으로 NotRunnable이 된다면, notify()나 notifyAll()을 해 줘야 Runnable로 돌아온다.
    4.1 wait()와 notify()
    class VideoShop{
    private Vector buffer = new Vector();
    public VideoShop(){
    buffer.addElement("은하철도999-0");
    buffer.addElement("은하철도999-1");
    }
    public synchronized String lendVideo() throws InterruptedException{
    Thread t = Thread.currentThread();
    if(buffer.size()==0){
    System.out.println(t.getName() + ": 대기상태진입");
    this.wait();
    System.out.println(t.getName() + ": 대기상태해제");
    }
    String v = (String)this.buffer.remove(buffer.size()-1);
    return v;
    }
    public synchronized void returnVideo(String video){
    this.buffer.addElement(video);
    this.notify();
    }
    }
    4.2 wait()와 notify()

    예제
    class Person2 extends Thread{
    public void run(){
    try{
    String v = WaitNotifyMain.vShop.lendVideo();
    System.out.println(this.getName() + ":" + v + " 대여");
    System.out.println(this.getName() + ":" + v + " 보는중\n");
    this.sleep(1000);
    System.out.println(this.getName() + ":" + v + " 반납");
    WaitNotifyMain.vShop.returnVideo(v);
    }catch(InterruptedException e){e.printStackTrace();}
    }
    }
    4.2 wait()와 notify()

    예제 - 테스트
    public class WaitNotifyMain{
    public static VideoShop vShop = new VideoShop();
    public static void main(String[] args){
    System.out.println("프로그램시작");
    Person2 p1 = new Person2();
    Person2 p2 = new Person2();
    Person2 p3 = new Person2();
    Person2 p4 = new Person2();
    p1.start();
    p2.start();
    p3.start();
    p4.start();
    System.out.println("프로그램종료");
    }
    }
    4.2 notifyAll()

    notify()를 호출하면 대기중의 스레드가 하나를 골라서 실행상태로 보내게 된다

    그러나 어떤 스레드를 선택할지는 내부의 구현에 따라 다르 다는 다소 모호한 설명이다(Java Doc)

    여하튼 대기상태에 빠져있는 스레드를 깨우는 역할을 하지 만 내부적으로 완벽하게 하나의 스레드를 깨워준다는 보장 을할수없다고한다.

    notify()의 이러한 부분을 보완해 주는 메서드가 notifyAll()이다.

    이는 대기중의 모든 스레드를 다 깨운다.
    4.2 notifyAll()
    class VideoShop3{
    private Vector buffer = new Vector();
    public VideoShop(){
    buffer.addElement("은하철도999-0");
    buffer.addElement("은하철도999-1");
    }
    public synchronized String lendVideo() throws InterruptedException{
    Thread t = Thread.currentThread();
    while(buffer.size()==0){
    System.out.println(t.getName() + ": 대기상태진입");
    this.wait();
    System.out.println(t.getName() + ": 대기상태해제");
    }
    String v = (String)this.buffer.remove(buffer.size()-1);
    return v;
    }
    public synchronized void returnVideo(String video){
    this.buffer.addElement(video);
    this.notifyAll();
    }
    }
    4.2 notifyAll()
    class Person3 extends Thread{
    public void run(){
    try{
    String v = NotifyAllMain.vShop.lendVideo();
    System.out.println(this.getName() + ":" + v + " 대여");
    System.out.println(this.getName() + ":" + v + " 보는중\n");
    this.sleep(1000);
    System.out.println(this.getName() + ":" + v + " 반납");
    NotifyAllMain.vShop.returnVideo(v);
    }catch(InterruptedException e){e.printStackTrace();}
    }
    }
    4.2 notifyAll()

    예제 - 테스트
    public class NotifyAllMain{
    public static VideoShop vShop = new VideoShop();
    public static void main(String[] args){
    System.out.println("프로그램시작");
    Person3 p1 = new Person3();
    Person3 p2 = new Person3();
    Person3 p3 = new Person3();
    Person3 p4 = new Person3();
    p1.start();
    p2.start();
    p3.start();
    p4.start();
    System.out.println("프로그램종료");
    }
    }
    5 Class getClass()
    5.1 등록정보 클래스

    우리가 만든 클래스는 .class파일로 변환된다.

    이 파일에는 모든 정보가 들어있다.

    멤버변수와 메서드

    상위클래스, 구현된 인터페이스

    생성자들의 정보가 있다.

    가상머신은 .class파일을 로딩한 후에애 비로소 객체 를 생성하거나 메서드를 호출할 수 있다.

    특정 클래스의 정보를 확인 할 수 있다면 Class클래 스를 이용하면 된다.

    예를 들어 Data클래스의 Class클래스를 얻고 싶다면,

    Class c = Data.class;
    5.1 등록정보 클래스

    Class 클래스란

    Class는 클래스의 정보 클래스이다.

    특정 클래스의 정보를 추출하는 방법은 Class의 멤버메서 드를 이용하면 된다.

    예를 들어, Class c로부터 클래스의 이름 얻기

    String name = c.getName();와같이하면된다.

    Class 클래스를 이용한 객체 생성

    Class c = Data.class;

    Object obj = c.newInstance();

    obj를 Data 클래스로 캐스팅을 하면 완벽한 객체가 태 어나게 되는 것이다.

    Data d = (Data)obj;
    5.2 getClass()

    getClass()메서드를 이용하기

    Object클래스 소속의 getClass()메서드를 이용하여 Class 클래스를얻을수도있다.

    일반적으로는 클래스를 이용하여 객체를 생성한다.

    하지만 여기에서는 getClass()를 이용해서 클래스를 얻어내고 있다.

    이러한 기법을 reflection이라고 한다.
    5.2 getClass()

    예제
    class Data{
    //내용없음
    }
    public class ReflectDataClassMain{
    public static void main(String[] args)
    throws InstantiationException, IllegalAccessException{
    Data d = new Data();
    Class c = d.getClass();
    Object obj = c.newInstance();
    System.out.println(obj);
    }
    }
    6 문자열
    6.1 문자열

    문자열

    문자열은 문자상수의 집합이다.

    자바에서 문자열은 String 클래스의 객체이다.

    문자열을 생성하는 방법 I

    String str1 = "Hello World!";

    String str2 = "Hello World!";

    str1, str2는 동일한 메모리를 point한다!

    문자열생성하는방법II

    String ntr1 = new String("Hello World!");

    String ntr2 = new String("Hello World!");

    ntr1, ntr2는 서로 다른 메모리를 point한다.
    "Hello World!"
    str1
    str2
    ntr1
    ntr2
    Heap 영역의 메모리 공간
    상수 풀 영역
    "Hello World!"
    "Hello World!"
    new String("Hello World!");
    new String("Hello World!");
    6.1 문자열

    문자열 결합하기

    String ntr3 = "Hello" + " " + "World!";

    문자열 내에 에스케이프(Escape) 문자의 사용

    String myString = "c:\\javasrc\\chap07";

    문자열의 길이

    문자열의 length() 메서드를 이용한다.

    문자열 결합

    concat() 메서드나 + 연산자를 이용해서 문자열을 결합시킨다.

    문자열 비교

    equals() 또는 compareTo() 메서드 문자열 비교를 할 수 있다.
    6.2 문자열의 주요 메서드

    문자열 검색

    indexOf()

    문자열을 첫 부분부터 검색하여 입력한 문자열을 제일 먼저 만나는 위치를 리턴한다.

    lastIndexOf()

    문자열을 마지막 부분부터 검색하여 입력한 문자열을 제일 먼저 만나는 위치를 리턴한다.
    6.2 문자열의 주요 메서드

    문자열 잘라내기

    substring()

    시작 위치와 끝위치를 매개변수로 주면 해단 구간을 추출해 서 문자열로 돌려준다.

    문자열 교체(자바 5.0부터)

    replace()

    문자열 내에 특정 문자열을 모두 교체한다.
    6.3 문자열 메서드 예제(자바 5.0)

    자바 5.0 static import 기능 사용한 예제
    import static java.lang.System.out;
    public class StringMethodMain{
    public static void main(String[] args){
    String str1 = new String("www.jabook.org");
    String str2 = new String("www.jabook.org");
    System.out.println("str1의길이:" + str1.length());
    System.out.println("str2의길이:" + str1.length());
    System.out.println("str1.equals(str2):" + str1.equals(str2));
    System.out.println("str1.compareTo(str2):" + str1.compareTo(str2));
    out.println("str1.concat(str2):" + str1.concat(str2));
    out.println("str1+str2:" +str1+str2);
    out.println("str1.indexOf(\"jabook\"):" + str1.indexOf("jabook"));
    out.println("str1.indexOf(\"jabook\"):" + str1.lastIndexOf("o"));
    out.println("str1.substring(4,10):" + str1.substring(4,10));
    out.println("str1.replace(\"o\",\"t\"):" + str1.replace("o", "t"));
    }
    }
    6.4 StringBuffer 클래스

    String 클래스는 수정이 불가능한(Immutable) 클래스!

    String str1 = "www.";

    String str2 = "jabook.";

    String str3 = "org";

    String str4 = str1 + str2 + str3; //새로운 문자열을 만들 어서 리턴한다.
    6.4 StringBuffer 클래스

    StringBuffer 클래스

    문자열의 수정이 가능한 클래스

    StringBuffer 클래스를 이용해 생성한 객체는 문자열의 추가, 삭제, 수정, 검색 등의 기능을 가지고 있다.

    StringBuffer 클래스는 수정이 가능한 클래스이다.

    StringBuffer sb = new StringBuffer();

    sb.append("www.");

    sb.append("jabook.");

    sb.append("org");

    sb.replace(11, 14, "net");

    String str = sb.toString();

    System.out.println(str);
    6.5 StringBuffer의 속도측정

    속도 측정 변수
    long startTime = 0L;
    long elapsedTime = 0L;

    String으로 문자열 만들기의 속도 측정
    String str1 = "";
    startTime = System.currentTimeMillis();
    for(int i=0; i<50000; i++){
    str1 += "H";//새로운문자열생성하기
    }
    elapsedTime = System.currentTimeMillis() -startTime;

    StringBuffer로 문자열 만들기의 속도 측정
    StringBuffer sb = new StringBuffer();
    startTime = System.currentTimeMillis();
    for(int i=0; i<50000; i++){
    sb.append("H");//새로운문자열추가하기
    }
    elapsedTime = System.currentTimeMillis() -startTime;
    6.5 StringBuffer의 속도측정

    예제
    class CalculateStringBuffer{
    public static void main(String[] args){
    long startTime = 0L;
    long elapsedTime = 0L;
    String str1 = "";
    startTime = System.currentTimeMillis();
    for(int i=0; i<50000; i++){
    str1 += "H"; //새로운문자열생성하기
    }
    elapsedTime = System.currentTimeMillis() -startTime;
    System.out.println("String속도: " + elapsedTime);
    StringBuffer sb = new StringBuffer();
    startTime = System.currentTimeMillis();
    for(int i=0; i<50000; i++){
    sb.append("H"); //새로운문자열추가하기
    }
    elapsedTime = System.currentTimeMillis() -startTime;
    System.out.println("StringBuffer속도: " + elapsedTime);
    }
    }
    6.5 StringBuffer의 속도측정

    실행결과

    실행할 때마다 다르며 String과 StringBuffer의 실행속도 간의 차이가 크다.

    String속도 : 6015

    StringBuffer속도 : 16
    6.6 StringBuilder 클래스(자바 5.0)

    StringBuilder 클래스

    StringBuffer는 동기화가 지원되는 반면,

    StringBuilder는 동기화가 지원되지 않는다.

    따라서 속도면에서 약간의 장점을 가진다.

    동기화 보장이 필요없는 문자열의 처리의 경우 이 클래스 를 이용하는 것이 좋다.
    6.6 StringBuilder 클래스(자바 5.0)

    예제
    class CalculateStringBuilder{
    public static void main(String[] args){
    long startTime = 0L;
    long elapsedTime = 0L;
    StringBuffer sb = new StringBuffer();
    startTime = System.currentTimeMillis();
    for(int i=0; i<50000; i++){
    sb.append("H"); //새로운문자열추가하기
    }
    elapsedTime = System.currentTimeMillis() -startTime;
    System.out.println("StringBuffer속도: " + elapsedTime);
    StringBuilder sb2 = new StringBuilder();
    startTime = System.currentTimeMillis();
    for(int i=0; i<50000; i++){
    sb2.append("H"); //새로운문자열추가하기
    }
    elapsedTime = System.currentTimeMillis() -startTime;
    System.out.println("StringBuilder속도: " + elapsedTime);
    }
    }
    6.6 StringBuilder 클래스(자바 5.0)

    실행결과

    실행할 때마다 다르며 StringBuilder과 StringBuffer의 실 행속도간의 차이가 크다.

    StringBuffer속도 : 0

    StringBuilder속도 : 16
    6.7 Formatting 기능(자바 5.0)

    포멧팅(Formatting) 기능

    자바 5.0 이전에는 Formatter 클래스를 이용해서 포멧된 문자열을 생성했지만, 자바 5.0부터는 String.format() 메서드를 이용해서 포멧 된 문자열을 만들 수 있다.

    포멧팅의 예

    String s1 = String.format("%s %d %f %o %h", "Hello", 100, 3. 14F, 100, 100);

    숫자 포멧팅의 예

    String s2 = String.format("%,d", 10000000);

    콤마(,)가 포함된 숫자

    String s3 = String.format("%.3f", 42.000000);

    소수점 3째 자리까지 표현

    String s4 = String.format("%,.2f ", 12345.678901);

    콤마가 포함되며, 소수점 2째 자리까지 표현
    6.7 Formatting 기능(자바 5.0)

    예제
    class FormattingTest{
    public static void main(String[] args){
    String s1 = String.format("%s %d %f %o %h", "Hello", 100, 3.14F,100,
    100);
    System.out.println("s1 : " + s1);
    String s2 = String.format("%,d", 10000000);
    System.out.println("s2 : " + s2);
    String s3 = String.format("%.3f", 42.000000);
    System.out.println("s3 : " + s3);
    String s4 = String.format("%,.2f ", 12345.678901);
    System.out.println("s4 : " + s4);
    }
    }
    6.7 Formatting 기능(자바 5.0)

    실행결과

    s1 : Hello 100 3.140000 144 64

    s2 : 10,000,000

    s3 : 42.000

    s4 : 12,345.68

    각 format별로 출력되는 양식을 확인하면 된다.
Designed by Tistory.