IsEmpty 반대 - isEmpty bandae

자바 객체 지향 프로그래밍자바, 더 정확하게!null 퀴즈

!str.isEmpty() 의미

왕궁

IsEmpty 반대 - isEmpty bandae

왕궁

IsEmpty 반대 - isEmpty bandae

질문 지켜보기를 시작하면 질문에 답변, 댓글이 달릴 때 알림을 받을 수 있어요.

IsEmpty 반대 - isEmpty bandae

2022년 1월 26일

다시 천천히 확인해보니 아마 문맥상흐름에 있어 오해가 있었던 것 같습니다. 해설에 보면 "두 번째 조건!str.isEmpty()은 문자열 str이 빈 문자열인지 확인합니다. strings[2].isEmpty()의 경우 true를 리턴하겠죠."라는 문장이 있습니다. 여기서 strings[2] = "" 빈문자열이기 때문에 strings[2].isEmpty()는 true값이지만 앞에 !가 붙음으로써 false가 되는 것이고, (str != null && !str.isEmpty())가 (true && false)이기 때문에 countB가 증가되는 것인데 곧바로 숏서킷연산 설명이 이어지면서 마치 strings[2]가 (false && true)라서 countB가 증가된다는 내용으로 헷갈렸던 것 같습니다.

질문 지켜보기를 시작하면 질문에 답변, 댓글이 달릴 때 알림을 받을 수 있어요.

목차

  1. isEmpty() 예제 - 빈 문자열인지 체크
  2. isEmpty() 정의
  3. isEmpty() 구문

isEmpty() 예제 - 빈 문자열인지 체크

Hz.java

public class Hz {

  public static void main(String[] args) {

    String s1 = "Homzzang.com";

    String s2 = "";

    System.out.println(s1.isEmpty()); // false

    System.out.println(s2.isEmpty()); // true

  }

}

isEmpty() 정의

문자열이 비였는지 여부 체크.

(= 빈 문자열인지 체크.)

isEmpty() 구문

public boolean isEmpty()


[매개변수]

없음.


[반환값]

boolean 자료형 반환.

  • 문자열이 빈 경우 (= 문자열 길이가 0인 경우)엔, true 반환.
  • 그렇지 않은 경우엔 false 반환.

둘은 언뜻 같아보이지만 다르다. 결론부터 말하면 isBlank는 공백을 true로 판단하고 Empty는 공백도 false로 판단한다.

값(value) isEmpty() isBlank()
null true true
"" true true
" " false true
"sdnfi" false false
" sdnfi " false false

둘 사이의 동작방식 차이는 무얼까? isEmpty를 살펴보자.

public inline fun CharSequence?.isNullOrEmpty(): Boolean {
    contract {
        returns(false) implies (this@isNullOrEmpty != null)
    }

    return this == null || this.length == 0
}

null 혹은 문자열의 길이가 0인지를 체크한다. isBlank는 찾아보지 않았지만 반대의 로직으로 동작할 것이다.(거기에 추가적으로 들어갈 순 있겠지만...^^)

이 게시물은 Java에서 목록이 비어 있는지 확인하는 방법에 대해 설명합니다.

1. 사용 List.isEmpty() 방법

Java에서 목록이 비어 있는지 확인하는 간단한 솔루션은 목록의 isEmpty() 방법. 목록에 요소가 없으면 true를 반환합니다. 피하기 위해 NullPointerException, 앞서다 isEmpty null 검사를 사용하여 메서드를 호출합니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

importjava.util.Collection;

importjava.util.List;

classMain

{

    public staticbooleanisEmpty(Collection<?> collection){

        returncollection== null||collection.isEmpty();

    }

    publicstaticvoid main(String[]args)

    {

        List<Integer>nums=List.of();

        booleanisEmpty= isEmpty(nums);

        if (isEmpty){

            System.out.println("The collection is empty");

        }else{

            System.out.println("The collection is not empty");

        }

    }

}

다운로드  코드 실행

결과:

The collection is empty

 
반대의 경우, 즉 목록이 비어 있지 않은지 확인하려면 다음 표현식을 사용할 수 있습니다.

importjava.util.List;

classMain

{

    publicstaticvoid main(String[]args)

    {

        List<Integer>nums=List.of();

        booleanisNotEmpty=nums!= null&&!nums.isEmpty();

        if(isNotEmpty){

            System.out.println("The collection is not empty");

        }else {

            System.out.println("The collection is empty");

        }

    }

}

다운로드  코드 실행

결과:

The collection is empty

2. Apache Commons Collections 사용하기

null 안전 버전을 얻으려면 isEmpty() 방법, 당신은 사용할 수 있습니다 CollectionUtils.isEmpty() Apache Commons Collections의 메소드.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

importorg.apache.commons.collections4.CollectionUtils;

importjava.util.List;

classMain

{

    publicstaticvoid main(String[]args)

    {

        List<Integer>nums=List.of();

        booleanisEmpty= CollectionUtils.isEmpty(nums);

        if (isEmpty){

            System.out.println("The collection is empty");

        }else{

            System.out.println("The collection is not empty");

        }

    }

}

코드 다운로드

결과:

The collection is empty

3. 목록 목록에서 비어 있거나 null 확인

목록 목록에서 빈 목록이나 null 값을 확인하려면 Stream API를 사용할 수 있습니다. 예를 들어,

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

importjava.util.Arrays;

import java.util.List;

classMain

{

    publicstaticbooleanisAnyEmpty(List<List<Integer>>listOfLists){

        return listOfLists.stream()

                .anyMatch(x->x==null ||x.isEmpty());

    }

    publicstaticvoidmain(String[] args)

    {

        List<List<Integer>>listOfLists=Arrays.asList(

                List.of(1,2,3),

                null,

                List.of(4,5)

        );

        booleanisAnyEmpty=isAnyEmpty(listOfLists);

        if(isAnyEmpty){

            System.out.println("The collection is empty");

        }else {

            System.out.println("The collection is not empty");

        }

    }

}

다운로드  코드 실행

결과:

The collection is empty

 
또 다른 대안은 다음을 사용하는 것입니다. contains() 목록에서 지정된 값을 확인하는 메서드입니다. 다음과 같이 사용할 수 있습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

importjava.util.Arrays;

import java.util.Collections;

import java.util.List;

classMain

{

    publicstaticbooleanisAnyEmpty(List<List<Integer>>listOfLists){

        return listOfLists.contains(null)|| listOfLists.contains(Collections.emptyList());

    }

    publicstaticvoid main(String[]args)

    {

        List<List<Integer>>listOfLists= Arrays.asList(

                List.of(1,2,3),

                List.of(),

                List.of(4,5)

        );

        booleanisAnyEmpty= isAnyEmpty(listOfLists);

        if (isAnyEmpty){

            System.out.println("The collection is empty");

        }else{

            System.out.println("The collection is not empty");

        }

    }

}

다운로드  코드 실행

결과:

The collection is empty

Java에서 목록이 비어 있는지 확인하는 것이 전부입니다.