2011-08-02 13 views
4

api doc said : 인덱스가 배열,리스트 또는 크기 크기의 문자열에서 유효한 요소를 지정하도록합니다.Google Guava의 Preconditions.checkElementIndex를 사용하는 방법?

하지만이 방법으로 '대상'배열 또는 목록 문자열을 전달할 수 있습니까?

+1

이것은 좋은 질문입니다. 이는 일관성없는 Java API가 얼마나 많은지를 보여줍니다. 나는 크기/길이를 가진 클래스들을위한 공통 인터페이스를 기대할 것이다. –

답변

1

int 인덱스가 지정된 크기의 목록, 문자열 또는 배열에 대해 유효한지 여부를 알기 위해 "대상"이 필요하지 않습니다. index >= 0 && index < [list.size()|string.length()|array.length]이면 유효하고 그렇지 않은 경우 유효합니다.

3

메소드 Precondition.checkElementIndex (...)는 '대상'에 대해 신경 쓰지 않습니다.

public String getElement(List<String> list, int index) { 
    Preconditions.checkElementIndex(index, list.size(), "The given index is not valid"); 
    return list.get(index); 
} 

Guava's reference에 따르면, checkElementIndex이 구현 될 수있는 방법은 다음과 같습니다 :

public class Preconditions { 
    public static int checkElementIndex(int index, int size) { 
    if (size < 0) throw new IllegalArgumentException(); 
    if (index < 0 || index >= size) throw new IndexOutOfBoundsException(); 
    return index; 
    } 
} 

당신이 볼 수 있듯이, 그것은 필요에가 없습니다 다음과 같이 간단하게 sizeindex 통과 List, Array 또는 무엇이든 알 수 있습니다.

6

Array, ListString의 요소는 0부터 시작하는 인덱스를 사용하여 액세스 할 수 있습니다.

if (index < 0) { 
     throw new IllegalArgumentException("index must be positive"); 
} else if (index >= list.size()){ 
     throw new IllegalArgumentException("index must be less than size of the list"); 
} 

목적 :

당신이, 당신이 IndexOutOfBoundsException을 방지하기 위해 0과 list.size()index가 확인하려면 다음 사용할 수 있습니다 list.get(index)를 호출 인덱스 .Before를 사용하여 목록에서 특정 요소에 액세스한다고 가정 Preconditions 클래스는

Preconditions.checkElementIndex(index,list.size()); 

하나 더 소형으로이 검사를 대체하는 것입니다 그래서, 당신은 .Instead 전체 대상 목록 인스턴스를 통과 할 필요가 없습니다, 대상 목록의 크기를이 메서드에 전달하면됩니다.

관련 문제