2014-04-19 3 views
-1

HashSet의 초기 용량은 어떻게됩니까?HashSet의 초기 용량은 어떻게 구합니까?

import java.util.*; 
import java.lang.reflect.Field; 
public class Demo 
{ 
    static int getCapacity(ArrayList<?> l) throws Exception 
    { 
     Field dataField = ArrayList.class.getDeclaredField("elementData"); 
     dataField.setAccessible(true); 
     return ((Object[]) dataField.get(l)).length; 
    } 
    public static void main(String args[]) 
    { 
     ArrayList a = new ArrayList(); 
     System.out.println(getCapacity(a)); 
     HashSet h = new HashSet(); //in case HashSet what we do 
     System.out.println(h.capacity()); 
    } 
} 

실제로는 HashSet 클래스에는 용량 방법이 없습니다. 그렇다면 용량을 어떻게 얻으시겠습니까 HashSet? HashSet 개체의 초기 용량을 어떻게 얻을 수 있습니까?

+0

왜? 그것을 알기 위해 어떤 좋은 일을합니까? – EJP

답변

1

HashSet 해당 정보가 노출되지 않습니다. 원하는 경우 초기 용량을 직접 설정할 수 있습니다 (예 : HashSet h = new HashSet(22);). javadoc은 기본 용량이 16임을 나타냅니다.

내부적으로 HashSetHashSet.map 필드를 통해 HashMap을 래핑합니다. map 필드를 가져 오기 위해 리플렉션을 사용하고 초기 용량에 대해 조사 할 수 있다고 가정합니다. 나는 왜 당신이 이것을하고 싶어하는지 알 수 없다.

+0

static int getCapacity (ArrayList l) 예외를 throw합니다. { 필드 dataField = ArrayList.class.getDeclaredField ("elementData"); dataField.setAccessible (true); return ((Object []) dataField.get (l)). length; } ArrayList = new ArrayList(); System.out.println (getCapacity (a)); - 다음 10과 같이 10 개 있습니다. – user3444725

+2

@ user3444725 여기에 뭐라 고 하시겠습니까? 귀하의 질문에 대답하면 upvote 대답을 수락하십시오. –

관련 문제