'자바 값 비교'에 해당되는 글 1건

728x90
You can not use .equals() to compare int.
But you can use == also to compare Integer.
Integer and int are different. Integer is a class and int is a primitive type.

public class IntegerToString {
    public static void main(String[] args) {
        // declare the Integer object
        Integer intValue = new Integer(100);
        // Declare the Object
        Object obj = new Integer(100);
        // test for equality
        if(intValue.equals(obj)){
            System.out.println("Integer is equals to the object.");
        }
        else{
            System.out.println("Not equal, something is wrong.");
        }
    }
}


결과 : Integer is equals to the object.


난독화 가이드에 String 비교시 == 를 사용하지 말라고 되어 있어서

if (deviceFound == null) {
대신에
if (!"".equals(deviceFound)) {
로 변경해서 난독화 하지 않은 상태로 시도했더니 에러가 발생한다.


즉, null 은 객체가 아니라서 equals 로 비교할 수가 없다.

!"".equals(deviceFound) 이 null 을 대신할 수는 없다는 것이다.


!"".equals(st)
형태로 많이 쓴다고 되어 있어서 테스트를 해봤는데 잘못된 정보다.

null 비교는 == 연산자를 사용하면 된다.


equals는 기본적으로 값 비교를 한다.
== 는 주소값을 비교한다.
String 객체를 == 연산자로 비교하면 '주소값' 을 비교한다.
비교 대상 중 primitive type(int) 의 변수가 하나라도 있다면, == 연산자는 값으로 비교한다.


private String IPSubnetMask(String msgArray){
    if(msgArray.contains("/")){
        String[] input_ipsubnet = msgArray.split("/"); // / 기호로 분리하라.
        String ipaddress = input_ipsubnet[0];
        String subnetMask = input_ipsubnet[1];
        if(IP_Validation.matcher(ipaddress).matches()) {
            if(Integer.parseInt(subnetMask)< 23) {
                return "3"; // 서브넷 마스크 확인 필요
            } else {
                return "1"; // 정상
            }
        } else {
            return "2"; // IP주소 비정상 입력
        }
    } else {
        return "0"; // 입력이 잘못되었다는 표시
    }
}


위 함수에서는 결과를 숫자가 아닌 문자 숫자로 반환하도록 했다.

String result = IPSubnetMask(ipsubnet);
if(result.equals("1")){

}

와 같이 equals 로 값 비교하면 된다.



'안드로이드 > Java 문법' 카테고리의 다른 글

[Java] Convert Month String to Integer  (0) 2019.10.14
Java ArrayList 함수 만들기  (0) 2019.10.02
공백으로 문자열 분리  (0) 2019.09.11
Java 제네릭(Generic)  (0) 2019.08.27
Java 추상 클래스  (0) 2019.08.19
블로그 이미지

Link2Me

,