![]() ![]() Since Vector is a concurrent collection, the size might change at any time before the call, so the caller cannot guarantee that the destination array is of sufficient size, nor can it know the number of elements copied. Not only does it not return the number of elements copied, it throws IndexOutOfBoundsException if the destination array is too short. But what if the array is too small? Well, maybe throw an exception. The array doesn't need to be returned, because the caller already has a reference to it. The caller passes in an array, which is reused, and the return value is the number of elements copied into it. OK, let's have an API that looks like this: int toArray(T a) Unlike the no-arg toArray() method, which returns an array of the right size, if the caller's array is re-used, we need to a way to return the number of elements copied. The caller wants to re-use an array, so it clearly needs to be passed in. Handling case (1) turns out to be a fairly subtle API problem. That's useful, but it doesn't satisfy a couple other use cases:ġ) The caller wants to re-use an existing array, if possible andĢ) The caller wants to specify the component type of the returned array. That is, the component type of the returned array is always Object. Note Arrays.asList creates a fixed size list while Collections.singletonList creates an immutable list and therefore does not allow operations like set (int index, E element). This takes the elements from the collection and returns them in an Object. Use Collections Singleton List Description Replaces Arrays.asList with 0 or 1 parameters respectively with Collections.emptyList () or Collections.singletonList (.). The T toArray(T a) method on Collection is weird, because it's trying to fulfill two purposes at once.įirst, let's look at toArray(). public static List singletonList (T o) Parameters o This is the sole object to be stored in the returned list.Declaration Following is the declaration for () method. ![]() So it clears the last element from the array, but why it would not do that in the first example? The singletonList (T) method is used to return an immutable list containing only the specified object. ![]()
0 Comments
Leave a Reply. |