자바 노트:포장 류,toString()방법,단일 클래스,비교(==equals 방법)

19238 단어 toString
1.포장 류
1)포장 류 는 기본 데이터 형식 에 해당 하 는 인용 데이터 형식 을 제공 합 니 다.(기본 데이터 형식-포장 류)btye-Byte,char-Character,short-Short,float-Floating-Integer,double-Double,long-Long,boolean-Boulean
2)포장 류 의 구조 기 를 통 해 실현 합 시다.기본 데이터 유형 은 포장 류 로 포장 합 니 다.
3)포장 류 의 xxxValue()인 스 턴 스 방법 을 사용 하여 포장 류 대상 에서 포장 하 는 기본 데이터 유형 을 얻 을 수 있다.
package cn.it.lsl;

public class Primitive2Wrapper {
    public static void main(String[] args) {
        boolean b = true;
        Boolean b1 = new Boolean(b);
        int a = 5;
        Integer a1 = new Integer(a);
        //               (Character   )
        Float f = new Float("2.3");
        Boolean b2 = new Boolean("false");
        
        boolean b3 = b2.booleanValue();
        System.out.println(b3);
        
        int aa = a1.intValue();
        System.out.println(aa);
        
        
        //          Boolean   ,         "true",                  , "True",    true   Boolean  
        //         ,    false   Boolean  
        Boolean b4 = new Boolean("true");
        boolean b5 = b4.booleanValue();
        System.out.println(b5);
    }
}

4)이상 의 전환 은 비교적 번 거 로 우 므 로 JDK 1.5 에서 자동 포장 과 자동 분해 기능 을 제공 하여 포장 류 와 기본 데이터 유형의 전환 을 실현 한다.자동 포장:기본 데이터 형식 을 대응 하 는 포장 류 에 직접 할당 하여 자동 으로 상 자 를 뜯 습 니 다.포장 류 를 대응 하 는 기본 데이터 형식 eg 에 직접 할당 합 니 다.
Integer a = 5;
int b = a;

5)포장 류 는 기본 유형 과 문자열 간 의 전환 도 실현 할 수 있다.문자열 형식의 값 을 기본 형식의 값 으로 변환(1)parseXxx(String s)방법(Charcater 제외)(2)패키지 클래스 가 제공 하 는 구조 기 를 이용 하여 기본 형식 을 문자열(1)String 클래스 의 value Of()(2)기본 형식 과"""로 연결 연산 하기
package cn.it.lsl;

public class Primitive2Wrapper {
    public static void main(String[] args) {        
        String str = "23";
        int a1 = Integer.parseInt(str);
        int a2 = new Integer(str);
        System.out.println(a1);
        System.out.println(a2);
        
        String str2 = String.valueOf(2.34f);
        System.out.println(str2);
        
        System.out.println(23+"");
    }
}

6)포장 류 의 비교(1)포장 류 는 기본 데이터 유형 과 비교 할 수 있다(2)포장 류 는 인용 데이터 유형 이기 때문에 두 개의 포장 류 가 한 대상 을 가리 킬 때 만 true 로 돌아간다.
Integer a = new Integer(6);
System.out.println("6        5.0:" + (a>5.0));
System.out.println("2       :" + (new Integer(2) == new Integer(2)));

7)포장 류 비교 의 특수 상황 자동 포장 결과
package cn.it.lsl;

public class Primitive2Wrapper {
    public static void main(String[] args) {
        Integer a = 2;
        Integer b = 2;
        System.out.println(a == b);   //  true
        
        Integer a1 = 128;
        Integer b1 = 128;
        System.out.println(a1 == b1);    //  false
        
    }
}

분석:상기 절 차 는 두 개의 2 자동 포장 후 비교적 같 지만 두 개의 128 자동 포장 후 같 지 않다.이 는 시스템 내부 에 캐 시 기능 을 제공 하여-128~127 사이 의 정 수 를 Integer 로 자동 으로 포장 할 때 실제 대상 을 가리 키 는 수치 요 소 를 직접 가리 키 고-128~127 범위 밖의 정수 가 Integer 로 자동 으로 포장 할 때 항상 Integer 인 스 턴 스 를 새로 만 들 기 때 문 입 니 다.
2.toString()방법 toString()은 Object 클래스 의 인 스 턴 스 방법 입 니 다.모든 클래스 가 Object 의 하위 클래스 이기 때문에 모든 자바 대상 은 toString()방법 을 가지 고 있 습 니 다.대상 을 인쇄 할 때 항상 toString()방법 을 호출 합 니 다.결 성 된 상태 에서 출력 할 때 클래스 이름,기호 이름@,대상 의 hashCode()값 입 니 다.
package cn.it.lsl;

public class ToStringWithout {
    int x;
    int y;
    public ToStringWithout(int x,int y){
        this.x = x;
        this.y = y;
    }
    public static void main(String[] args) {
        System.out.println(new ToStringWithout(23,33));
    }
}

출력:cn.it.lsl.ToStringWithout@bb0d0d
package cn.it.lsl;
//  toString()  
public class ToStringWith {
    int x;
    int y;
    public ToStringWith(int x, int y){
        this.x = x;
        this.y = y;
    }
    public String toString(){
        return "ToStringWith[" + x + "," + y + "]";
    }
    public static void main(String[] args) {
        System.out.println(new ToStringWith(23,33));
    }
}

출력:ToStringWith[23,33]
3.하나의 예 류 는 하나의 인 스 턴 스 를 자 유 롭 게 만 들 수 없 으 며,이러한 종류의 대상 만 만 만 들 수 있 습 니 다.이것 이 하나의 예 류 입 니 다.1)단일 클래스 를 만 드 는 방법(1)구조 기 를 private 로 수식 하면 다른 클래스 가 자 유 롭 게 이러한 인 스 턴 스 를 만 드 는 것 을 피 할 수 있 습 니 다.(2)이러한 접근 점 으로 대상 을 만 드 는 데 사용 되 는 Public 방법 을 제공 하고 이 방법 은 static 수식 을 사용 해 야 합 니 다.(이 방법 을 호출 할 때 대상 이 존재 하지 않 기 때문에 이 방법 을 호출 하 는 것 은 클래스)(3)이 클래스 에 캐 시 대상 이 있어 야 합 니 다.이 클래스 가 대상 을 만 들 었 는 지 여 부 를 판단 하 는 데 사 용 됩 니 다.그래 야 하나의 대상 만 만 만 들 수 있 습 니 다.이 구성원 도 static 로 수정 해 야 합 니 다.
package cn.it.lsl;

class Singleton{
    //                
    private static Singleton instance;
    private Singleton(){}
    
    public static Singleton getInstance(){
        /*   instance null,     Singleton  
         *   instance  null,        Singleton  ,     
         * */
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

public class SingletonTest {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);
    }
}

4.비교(==equals 방법)1)를 사용 하면==두 인용 유형 변 수 를 비교 할 때 같은 대상 을 가리 킬 때==판단 이 true 입 니 다.2)두 변 수 를 비교 할 때 기본 유형 이 고 모두 수치 유형 일 때 두 값 이 같 으 면 true 로 돌아 갑 니 다.예 를 들 어:
int a = 65;
float b = 65.0f;
System.out.println(a == b);
char c = 'A';
System.out.println(a == c);

3)"hello"의 직접 양 과 new String("hello")의 차 이 는?(1)상수 탱크 의 개념:컴 파일 기간 이 확정 되 고 컴 파일 된 class 파일 에 저 장 된 데 이 터 를 관리 하 는 데 사 용 됩 니 다.(2)자바 프로그램 이'hello'와 같은 문자열 을 직접 사용 할 때(컴 파일 할 때 계산 할 수 있 는 문자열 값 포함)JVM 은 상수 풀 을 사용 하여 이 문자열 을 관리 합 니 다.(3)new String("hello")을 사용 할 때 JVM 은 상수 풀 을 사용 하여"hello"의 직접 양 을 관리 한 다음 String 류 의 구조 기 를 호출 하여 새로운 String 대상 을 만 들 고 새로 만 든 String 대상 은 메모리 에 저 장 됩 니 다.바로 뉴 스 트 링(hello)이 두 개의 대상 을 만 들 었 다 는 것 이다.
package cn.it.lsl;

public class EqualDemo {
    public static void main(String[] args) {
        String s1 = "  ";
        String s2 = " ";
        String s3 = " ";
        String s4 = " " + " ";        //s4                  
        String s5 = s2 + s3;        //s5                  
        String s6 = new String("  ");
        
        System.out.println(s1 == s4);
        System.out.println(s1 == s5);
        System.out.println(s1 == s6);
    }
}

JVM 상수 탱크 는 같은 문자열 의 직접 수량 이 하나 밖 에 없 으 며 여러 개의 복사 본 이 생 성 되 지 않 습 니 다.
4)equals 방법(1)equals 방법 은 Object 류 가 제공 하 는 인 스 턴 스 방법 이기 때문에 모든 인용 변 수 는 이 방법 을 호출 할 수 있 습 니 다.그러나 이 방법 은 이 두 대상 이 같은 기준 과 사용=연산 자 를 판단 하 는 것 과 다 르 지 않 습 니 다.마찬가지 로 두 인용 변수 가 같은 대상 을 가리 킬 때 만 true 로 돌아 갑 니 다.(2)String 은 Object 의 equals()방법 을 다시 썼 습 니 다.String 의 equals()방법 은 두 문자열 이 같은 지 여 부 를 판단 하 는 기준 은 두 문자열 의 문자 서열 이 같 으 면 true 로 돌아 가 는 것 입 니 다.(3)Object 가 기본적으로 제공 하 는 equals()는 비교 대상 의 주소 일 뿐,대부분의 경우 equals()방법 을 다시 써 야 합 니 다.
package cn.lsl;

class Person{
    private String name;
    private String id;
    
    public Person() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public Person(String name, String id) {
        super();
        this.name = name;
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    
    public boolean equals(Object obj){
        if(this == obj)
            return true;
        //obj  null,   Person      
        if(obj != null && obj.getClass() == Person.class){
            Person personObj = (Person)obj;
            if(this.getId().equals(personObj.getId())){
                return true;
            }
        }
        return false;
    }
    
}

public class OverrideEqualsRight{
    public static void main(String[] args) {
        Person p1 = new Person("   ","1213");
        Person p2 = new Person("  ","1213");
        Person p3 = new Person("  ","1215");
        System.out.println(p1.equals(p2));
        System.out.println(p2.equals(p3));
    }
}

좋은 웹페이지 즐겨찾기