Data AccessCore JavaApp FrameworksViewTestingBuildingDeploymentDev ToolsSecurityOpinions

Tuesday, January 27, 2009

java.util.List to Object array (Object []) of a specified type

The tip below can help you in the data access tier or the application tier.

The java.lang.reflect.Array class provides static methods to dynamically create and access Java arrays. Any java collection or list can easily be converted into an Object array. There are two method calls, that I preferably squish into one line to get the job done. The first method call is:

Array.newInstance(Class componentType, int length) throws NegativeArraySizeException 


The method creates a new array with the specified component type and length. You can also cast down to have returned an array of your specified component type.

The second method call is defined in the java.util.List interface.

public Object[] toArray(Object[] a)


The method returns an array containing all of the elements in the List in the correct order where the runtime type of the returned array is that of the specified array.

Coupling the two calls above can allow you to quickly transform your ArrayList of objects into an object array of the specified object's component type.

Have a look at the sample code below for an ArrayList of strings to be converted into a String [].

ArrayList theStrings = new ArrayList();
theStrings.add("Hello");
theStrings.add("Aloha");
theStrings.add("Bonjour");

//Return String [].
String [] theStringArray = 
(String[])theStrings.toArray(
(String[])Array.newInstance(java.lang.String.class, theStrings.size())
);


With one line, you'll be able to turn your list of Java objects into an array of objects of the object's component type.

Questions, just comment and I'll be sure to get back to you.

4 comments:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Java Training in Chennai | Core Java Training in Chennai

    Online Java Training Java Online Training | Java J2EE Online Training | JavaEE Training Institute in Chennai

    ReplyDelete
  2. Movers and Packers Hisar
    Packers and Movers, Movers and Packers, Movers and Packers Commercial Relocation Services,Movers and Packers Household Relocation Services, Movers and Packers Office Relocation Services, Movers and Packers Hisar, Movers and Packers Sirsa Road, Movers and Packers Housing Board Colony.Packers and Movers, Movers and Packers, Movers and Packers Commercial Relocation Services,Movers and Packers Household Relocation Services, Movers and Packers Office Relocation Services, Movers and Packers Hisar, Movers and Packers Sirsa Road, Movers and Packers Housing Board Colony
    http://www.agarsainpackers.com/packers-and-movers-hisar.html

    ReplyDelete