Skip to main content

How to use the toArray() method of Collection?

--
There are two versions of toArray() in the Collection interface: Object[] toArray() without parameter and Object[] toArray(Object[] a) with parameter. toArray() without parameter will always return an array of type Object[] that you won't be able to cast. The toArray(new String[0]) will return an array of type Object[] that you may cast to String[].

The toArray() and toArray(Object[] a) method act as bridge between array-based and collection-based APIs. Further, the toArray(Object[] a) method allows precise control over the runtime type of the output array, and may, under certain circumstances, be used to save allocation costs.
The following is from the Javadoc:

public Object[] toArray()
Returns an array containing all of the elements in this collection. If the collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order. The returned array will be "safe" in that no references to it are maintained by the collection. (In other words, this method must allocate a new array even if the collection is backed by an Array). The caller is thus free to modify the returned array.
This implementation allocates the array to be returned, and iterates over the elements in the collection, storing each object reference in the next consecutive element of the array, starting with element 0.
public T[] toArray(T[] a)
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection. If the collection fits in the specified array with room to spare (i.e., the array has more elements than the collection), the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the collection only if the caller knows that the collection does not contain any null elements.)
If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
This implementation checks if the array is large enough to contain the collection; if not, it
allocates a new array of the correct size and type (using reflection). Then, it iterates over the collection, storing each object reference in the next consecutive element of the array, starting with element 0. If the array is larger than the collection, a null is stored in the first location after the end of the collection.
This method throws NullPointerException, if the specified array is null; or ArrayStoreException, if the runtime type of the specified array is not a supertype of the runtime type of every element in this collection.
Let's take a look at the following example. Suppose ll is a List known to contain only strings. The following code can be used to dump the list into a newly allocated array of String:
List ll = new ArrayList(); 
ll.add("java");      
ll.add("faq");  

String[] x = (String[]) ll.toArray(new String[ll.size()]);
out.println(x[0] + "\n" + x[1]);
Note that toArray(new String[ll.size()]) returns an String array of the elements in the list ll.

Comments

Popular posts from this blog

Asynchronous Vs. Synchronous Communications

Synchronous (One thread):   1 thread -> |<---A---->||<----B---------->||<------C----->| Synchronous (multi-threaded):   thread A -> |<---A---->| \ thread B ------------> ->|<----B---------->| \ thread C ----------------------------------> ->|<------C----->|

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol