Programing

Java가 크기 0의 배열을 허용하는 이유는 무엇입니까?

lottogame 2020. 10. 23. 07:31
반응형

Java가 크기 0의 배열을 허용하는 이유는 무엇입니까?


Java의 배열은 길이가 고정되어 있습니다. Java가 크기 0의 배열을 허용하는 이유는 무엇입니까?

String[] strings = new String[0];

비어 있음을 나타냅니다. 즉, 항목이 있고 결과가 발생하지 않는 것처럼 반복 할 수 있습니다.

for(int k = 0; k < strings.length; k++){
   // something
}

따라서 확인할 필요가 없습니다. 문제의 배열이 null이면 예외가 발생하지만이 경우에는 아무 작업도 수행하지 않으므로 적절할 수 있습니다.


Java가 크기 1의 배열을 허용하는 이유는 무엇입니까? 단일 값을 배열로 래핑하는 것은 꽤 쓸모가 없습니까? Java가 크기 2 이상의 배열 만 허용하면 충분하지 않을까요?

예, 우리 null는 빈 배열 대신 단일 객체 또는 크기 1 행렬 대신 기본 요소를 전달할 수 있습니다 .

그러나 그러한 제한에 대해 몇 가지 좋은 주장이 있습니다. 내 개인적인 주요 주장 :

제한이 너무 복잡하고 실제로 필요하지 않습니다.

배열의 크기를 [1..INTEGER.MAX_INT]로 제한하려면 코드 에 많은 추가 boudary 검사, (Konrads 의견에 동의) 변환 논리 및 메서드 오버로드를 추가해야합니다. 허용 된 어레이 크기에서 0 (또는 1)을 제외하면 비용이 절감되지 않으며 추가 노력이 필요하며 성능에 부정적인 영향을 미칩니다.

배열 모델 벡터

배열은 벡터에 대한 좋은 데이터 모델 (수학, 하지Vector 클래스!). 물론 수학의 벡터는 0 차원 일 수 있습니다. 존재하지 않는 것과 개념적으로 다릅니다.


사이드 노트 -(char-) 배열의 눈에 띄는 래퍼가 String클래스입니다. 불변 String은 빈 배열의 개념을 구체화합니다 : 빈 문자열 ( "")입니다.


때로는 null보다 크기가 0 인 배열을 반환하는 것이 훨씬 더 친숙합니다.


이것을 고려하십시오 (정오의 대답에 대한 더 자세한 설명) :

public String[] getStrings() {
 if( foo ) {
  return null;
 } else {
  return new String[] {"bar, "baz"};
 }
}

String[] strings = getStrings();
if (strings != null) {
 for (String s : strings) {
  blah(s);
 }
}

이제 이것을 다음과 비교하십시오.

public String[] getStrings() {
 if( foo ) {
  return new String[0];
 } else {
  return new String[] {"bar, "baz"};
 }
}

// the if block is not necessary anymore
String[] strings = getStrings();
for (String s : strings) {
 blah(s);
}

이것은 (null 값이 아닌 빈 배열을 반환) 실제로 Java API 디자인 세계에서 모범 사례입니다.

게다가 Java에서는 목록 (예 : ArrayList)을 배열로 변환 할 수 있으며 빈 목록을 빈 배열로 변환하는 것만이 의미가 있습니다.


C ++와 동일하므로 데이터가 없을 때보다 깔끔하게 처리 할 수 ​​있습니다.


길이가 0 인 배열이 유용 할 수있는 또 다른 경우 : 목록의 모든 요소를 ​​포함하는 배열을 반환하려면 :

<T> T[ ] toArray(T[ ] a)

길이가 0 인 배열을 사용하여 배열 유형을이 메서드에 전달할 수 있습니다. 예를 들면 :

ClassA[ ] result = list.toArray(new ClassA[0]);

길이가 0 인 배열은 여전히 ​​요소가 0 인 Object의 인스턴스입니다.


One case I can think of where an empty array is extremely useful is to use it instead of null in a situation where null isn't allowed. One possible example of that is a BlockingQueue of arrays. When you want to signal the end of input to the reading side, what would you do? To send null seems like an obvious choice, but the thing is that BlockingQueue doesn't accept nulls. You could wrap your array inside a class with "boolean last;" kind of field, but that's kind of overkill. Sending an empty (zero-sized) array seems like the most reasonable choice.


Another case when a zero length array is useful is when copying a two dimensional array. I can write:

public int[][] copyArray(int[][] array){
     int[][] newArray = new int[array.length][0];
     for(int i=0;i<array.length;i++){
         newArray[i] = array[i];
     }
     return newArray;

Being that every array reference in array is being overwritten, initializing them as refernces to zero length arrays is most efficient.


A 0-length byte[], or char[] can represent an empty String, which is distinct from null. Getting the bytes, or characters, as arrays from strings (using getBytes(), getChars() of String class etc.) and the vice-versa of forming Strings from byte[], char[] is quite common. For example, for custom encoding, decoding of strings.

참고URL : https://stackoverflow.com/questions/4612471/why-does-java-allow-arrays-of-size-0

반응형