How to create an array with Generic type?

Hi,
I need to create a typed array T[] from an object array Object[]. This is due to legacy code integration with older collections.
The method signature is simple:public static <T> T[] toTypedArray(Object[] objects)I tried using multiple implementations and go over them in the debugger. None of them create a typed collection as far as I can tell. The type is always Object[].
A simple implementation is just to cast the array and return, however this is not so safe.
What is interesting is that if I create ArrayList<String>, the debugger shows the type of the array in the list as String[].
If I create ArrayList<T>, the class contains Object[] and not T[].
I also triedT[] array = (T[]) Array.newInstance(T[].class.getComponentType(), objects.length);And a few other combinations. All work at runtime, create multiple compilation warnings, and none actually creates T[] array at runtime.
Maybe I am missing something, but Array.newInstace(...) is supposed to create a typed array, and I cannot see any clean way to pass Class<T> into it.T[].class.getComponentType()Returns something based on object and not on T, and T.class is not possible.
So is there anything really wrong here, or should I simply cast the array and live with the warnings?
Any help appreciated!

Ok. May be you could keep information about generic type in the your class:
public class Util {
    public static <T> T[] toTypedArray(Class<T> cls, Object[] objects){
        int size = objects.length;
        T[] t = (T[]) java.lang.reflect.Array.newInstance(cls, size);
        System.arraycopy(objects, 0, t, 0, size);
        return t;
public class Sample<T> {
    Class<T> cls;
    T[] array;
    public Sample(Class<T> cls) {
        this.cls = cls;
    public void setArray(Object[] objects){
        array = Util.toTypedArray(cls, objects);
    public T[] getArray(){
        return array;
    public static void main(String[] args) {
        Object[] objects = new Object[] { new LinkedList(), new ArrayList()};
        Sample<List> myClass = new  Sample<List>(List.class);
        myClass.setArray(objects);
        for(List elem: myClass.getArray()){
            System.out.println(elem.getClass().getName());
}

Similar Messages

  • How to create 2D array with 3 rows and unlimit column?

    how to create 2D array with 3 rows and unlimit column?

    Here are images of what I described in my previous post
    Message Edited by JoeLabView on 11-14-2007 07:56 AM
    Attachments:
    2D-array_code.PNG ‏7 KB
    2D-array_values.PNG ‏13 KB

  • How to create an array of generics?

    I have the following snippet of code using array of vectors:
    Vector[] tmpArr = new Vector[n];
    for(int j=0; j<n; j++)
    tmpArr[j] = new Vector();
    String str = ...
    if (!tmpArr[j].contains(str))
    tmpArr[j].add(str);
    And I want to convert to generics:
    Vector<String>[] tmpArr = new Vector<String>[n];
    for(int j=0; j<n; j++)
    tmpArr[j] = new Vector<String>();
    String str = ....
    if (!tmpArr[j].contains(str))
    tmpArr[j].add(str);
    But the first row gives me an error:
    -->Generic array creation.
    If I change it in
    Vector<String>[] tmpArr = new Vector<String>[n];
    (as I've seen in a pdf by G.Bracha talking aout collections)
    it gives me the error:
    -->cannot find symbol
    -->method add(String)
    in the
    tmpArr[j].add(str);
    row.
    The only way it seems to work is
    Vector<String>[] tmpArr = new Vector[n];
    but it gives me the unchecked conversion warning.
    How can I create an array of generics?
    Thank you!
    Matteo

    You can't
    Actually, that depends on the exact definition of a generic array. If by generic array someone means "an array comprised of elements defined by a type parameter", there is a solution.
    import java.lang.reflect.Array;
    public class Something<T> {
        private final Class<T> type;
        public Something(Class<T> type) {
            this.type = type;
        public String getTypeName() {
            return this.type.getName();
        public T[] newArray(final int length) {
            return (T[]) Array.newInstance(this.type, length);
    }The constructor introduces the type information (T) to the runtime environment, which means an instance of Something will know its type. Method newArray therefore does not cause a warning on unchecked type conversion, so this approach is typesafe.
    // Type parameter class is demanded by constructor...
    Something<String> stringThing = new Something<String>(String.class);
    // Cheating won't work, because the compiler catches the error...
    Something<Vector> vectorThing = new Something<Vector>(Integer.class);This approach, however, doesn't enable you to create an array of typed elements (like Vector<String>[]). If that is the definition of a generic array, then it is indeed not possible to create one.
    After all, while Vector[].class exists and can be resolved at runtime, there's no such thing as Vector<String>[].class, so there's no way you could provide the class definition of the component type to the constructor of Something.
    This may be a surprise to mdt_java, because if I remember correctly, templates in C++ cause actually different classes to be created for 'generic' types. This is not the case with Java.

  • How to create an item with date type mm/yyyy (no day)

    Hello,
    Is it possible to create an item with date type mm/yyyy (no day)? I want the pop-up date picker to just show month and year.
    Thanks,
    Jen

    Hi,
    you cannot pop-up date picker to just show month and year, but you can set your item format as MM-YYYY
    You can check this APEX_ITEM.DATE_POPUP2 at : http://docs.oracle.com/cd/E23903_01/doc/doc.41/e21676/apex_item.htm#CHDJHBCG (if using apex 4.1) else http://docs.oracle.com/cd/E10513_01/doc/apirefs.310/e12855/apex_item.htm#CHDFDDEI
    Edited by: Sergio_doudou on 2012-04-13 14:26

  • How to create a array with variables dimensions?

    I try to create a array like that:
    Object[][] data;
    data = new Object[] [];
    But that's doesn't work!
    Apparently I must specify the dimension of my array
    So I have done like that :
    Object[][] data;
    data = new Object[3] [3];
    And that work!
    But the problem is when I need to add extra elements to my array.
    If I write :
    data[4][1] = "123";
    I have the error message :
    java.lang.ArrayIndexOutOfBoundsException
    So, how can I defined a array with variables dimensions OR how can I add a dimension to a array?

    if you have:
    Object[][] data;
    data = new Object[3] [3];you end yo getting ArrayIndexOutOfBoundException if you try to point to some other Indexes. You can increase the size by doing new:
    Object[][] data;
    data = new Object[4] [3];and then copy the old Arrays to this one... this is heavy.
    Other thing to consider then is using some other datastructure, such as Vector, which grows along you add elements to it.
    P_trg

  • How to create an array with controls and indicators?

    I want to create a scrollable array of control/indicator pairs from a config file.  Something that looks like the attached image.  Of course, I can only create an array that's either either a control or indicator -- not both (the operator should not be able to edit the name or change the state of the LED).  So I guess I need to split the array and have two side-by-side and SOMEHOW link the scrollbars.  But then I have no idea how I can get the control switch states from the array.  Is there an easier way to do what I'm trying to do?
    Attachments:
    New Bitmap Image.JPG ‏11 KB

    Hello,
    Another option would be to use the custom control I built for you, see below.  You can just drop this into an array, it should look like your example (more or less).
    Cheers!
    CLA, CLED, CTD,CPI, LabVIEW Champion
    Platinum Alliance Partner
    Senior Engineer
    Using LV 2013, 2012
    Don't forget Kudos for Good Answers, and Mark a solution if your problem is solved.
    Attachments:
    Custom Switch.ctl ‏8 KB

  • How to create an array with a resultset

    Hello,
    Can somebody suggest a good way to put the result set of a query of a standard table into an array?
    The result set will have 0 to many rows. I can copy the rows into the array one row at a time, but I don't know what size array to create at the start.
    Any suggestions are greatly appreciated.
    Thank you,
    Logan

    ***The Following code will return u the ArrayList Object From ur resultset******
    public static ArrayList resultSetToArrayList(ResultSet rs){
              ArrayList results = null;
              try{
                        ResultSetMetaData md = rs.getMetaData();
                        int columns = md.getColumnCount();
                        results = new ArrayList();
                        while (rs.next()){
                             HashMap row = new HashMap();
                             results.add(row);
                             for(int i=1; i<=columns; i++){
                                  row.put(md.getColumnName(i),rs.getObject(i));
              catch(Exception e)
                   e.printStackTrace();
    return results;
    }

  • How to create a webservice with return type File

    Hi All,
    I have a class Letter and I am trying to expose viewReport as webservice.
    In Jdeveloper -> Business teir -> webservices -> Java web service and I have selected my method i.e. viewReport
    Now it throws error "The return type java.io.File of method viewReport can not be serialized into XML"
    I unserstood the issue but How can I achive this in JDeveloper
    public class Letter {
    public Letter() {
    super();
    public File viewReport(String name) {
    File folder = new File("C:\\APPS\\root\\pdf\\10052011");
    File[] listOfFiles = folder.listFiles();
    return listOfFiles[0];
    }

    You can't as File is nor serializable. It won't make sense as you would try to give a handle to a file on the server hosting the service to a remote system.
    Can you explain the use case in more detail?
    Timo

  • HT2534 Its is fake . i have bought iphone today but i haven't cred card so how i create account ? Your example type "none" window not come . New iphone but with out ID useless Phone :(

    Its is fake . i have bought iphone today but i haven't cred card so how i create account ? Your example type "none" window not come . New iphone but with out ID useless Phone

    Most of the people on these forums, including myself, are fellow users - you're not talking to iTunes Support here.
    Did you follow the instructions on that page exactly when creating the account (the instructions won't work with existing accounts) ? e.g. if doing it on your phone and you are currently logged into an account then log out of it, find a free app in the app store app, tap on its free price button, tap 'install app', and then tap on 'create new apple id' on the popup that you get. I tried those instructions on my phone a few days ago in response to another thread and I got the 'none' option on the payments screen.

  • How to create an array of a cluster?

    Hello!
    Now we need some help or tip again :-) We have an array of strings coming out from a for-loop. We want to pick this array in peaces and get the string-elements out. These elements we want to get into a cluster together with boolean constant. Of this cluster we then want to create an array. The problem is that we do not know how to overcome the trouble with data-types and for-loopes... *scratching our head...* Anyone? Thank you

    Hello Ex-jobb,
    have a look at my example. I included a second way to build your array of cluster.
    The string generation at the left of the diagram is to simulate your text file reading, it also gives you an array of strings.
    This array is in the upper part converted by using autoindexing of an for-loop. In the lower part I used just an "Index Array" with
    "Build cluster" and "build array".
    Hope this helps,
    GerdW
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome
    Attachments:
    ArrayOfCluster.vi ‏29 KB

  • How to create a node with attributes at runtime in webdynpro for ABAP?

    Hi Experts,
             How to create a node with attributes at runtime in webdynpro for ABAP? What classes or interfaces I should use? Please provide some sample code.
    I have checked IF_WD_CONTEXT_NODE_INFO and there is ADD_NEW_CHILD_NODE method. But this is not creating any node. I this this creates only a "node info" object.
    I even check IF_WD_CONTEXT_NODE but i could not find any method that creates a node with attribute.
    Please help!
    Thanks
    Gopal

    Hi
       I am getting the following error while creating a dynamic context node with 2 attributes. Please help me resolve this problem.
    Note
    The following error text was processed in the system PET : Line types of an internal table and a work area not compatible.
    The error occurred on the application server FMSAP995_PET_02 and in the work process 0 .
    The termination type was: RABAX_STATE
    The ABAP call stack was:
    Method: IF_WD_CONTEXT_NODE~GET_STATIC_ATTRIBUTES_TABLE of program CL_WDR_CONTEXT_NODE_VAL=======CP
    Method: GET_REF_TO_TABLE of program CL_SALV_WD_DATA_TABLE=========CP
    Method: EXECUTE of program CL_SALV_WD_SERVICE_MANAGER====CP
    Method: APPLY_SERVICES of program CL_SALV_BS_RESULT_DATA_TABLE==CP
    Method: REFRESH of program CL_SALV_BS_RESULT_DATA_TABLE==CP
    Method: IF_SALV_WD_COMP_TABLE_DATA~MAP_FROM_SOURCE_DATA of program CL_SALV_WD_C_TABLE_V_TABLE====CP
    Method: IF_SALV_WD_COMP_TABLE_DATA~MAP_FROM_SOURCE of program CL_SALV_WD_C_TABLE_V_TABLE====CP
    Method: IF_SALV_WD_COMP_TABLE_DATA~UPDATE of program CL_SALV_WD_C_TABLE_V_TABLE====CP
    Method: IF_SALV_WD_VIEW~MODIFY of program CL_SALV_WD_C_TABLE_V_TABLE====CP
    Method: IF_SALV_WD_COMPONENT~VIEW_MODIFY of program CL_SALV_WD_A_COMPONENT========CP
    My code is like the following:
    TYPES: BEGIN OF t_type,
                CARRID TYPE sflight-carrid,
                CONNID TYPE sflight-connid,
             END OF t_type.
      Data:  i_struc type table of t_type,
      dyn_node   type ref to if_wd_context_node,
      rootnode_info   type ref to if_wd_context_node_info,
      i_node_att type wdr_context_attr_info_map,
      wa_node_att type line of wdr_context_attr_info_map.
          wa_node_att-name = 'CARRID'.
          wa_node_att-TYPE_NAME = 'SFLIGHT-CARRID'.
          insert wa_node_att into table i_node_att.
          wa_node_att-name = 'CONNID'.
          wa_node_att-TYPE_NAME = 'SFLIGHT-CONNID'.
          insert wa_node_att into table i_node_att.
    clear i_struc. refresh i_struc.
      select carrid connid into corresponding fields of table i_struc from sflight where carrid = 'AA'.
    rootnode_info = wd_context->get_node_info( ).
    rootnode_info->add_new_child_node( name = 'DYNFLIGHT'
                                       attributes = i_node_att
                                       is_multiple = abap_true ).
    dyn_node = wd_context->get_child_node( 'DYNFLIGHT' ).
    dyn_node->bind_table( i_struc ).
    l_ref_interfacecontroller->set_data( dyn_node ).
    I am trying to create a new node. That is
    CONTEXT
    - DYNFLIGHT
    CARRID
    CONNID
    As you see above I am trying to create 'DYNFLIGHT' along with the 2 attributes which are inside this node. The structure of the node that is, no.of attributes may vary based on some condition. Thats why I am trying to create a node dynamically.
    Also I cannot define the structure in the ABAP dictionary because it changes based on condition
    Message was edited by: gopalkrishna baliga

  • How to create a complaint with pre-decessor document Inovice?

    Hello experts,
    I need create a complaint with reference to a pre-decessor document type Invoice (apart from other types such as sales order and service order). Can someone enlighten me
    1) how to create an invoice in IC Web Client and backend?
    2) how to create a complaint with reference to this created invoice in IC Web client and backend?
    Thanks a lot!!!

    Hi Easwar
    Thanks  a lot for answering the question.
    Yes I do have CRM Billing documents. But the problem is
    a) either the billing document doesn't have Transfer to Accounting status Transferred or
    b) a transferred billing document, but all items have error "Unable to offset billing item 90003458 0000000060" etc.
    Do you know
    1) how I can make a billing document have "Transferred" status? Pressing "Transfer to Accounting" button in the billing document overview page will only set the status to "Being transferred". And it's always being tranfered.
    2) What does the error "Unable to offset billing item ... "mean? How to get rid of them?
    Thanks a lot!

  • How to create shipment document with out inbound delivery document

    Dear Friends
    How to create shipment document with out outbound/inbound delivery document.
    In my client scenario, there is no inbound delivery for normal purchases.
    Just there are raising the PO to vendor, then they are doing MIGO for goods receipt.
    Can we do shipment creation with reference to PO?
    If it is possible, how it will be?
    Please let it solve
    With regards
    Lakshmikanth

    Dear Sameer,
    Please go to transaction VT01N here you enter Transportation planning point and shipment type then press enter.
    Now system will take you to the shipment document creation screen here you click on Select deliveries or press F6 now system will take you to the select outbound deliveries screen in this screen you enter selection data then execute, now deliveries will get assigned to that shipment.
    After assigning the deliveries enter the remaining data then complete the shipment finally save the shipment document.
    For more information please go through this SAP help link
    Note:- Shipment process need to be carry out for the deliveries before PGI.
    http://help.sap.com/saphelp_47x200/helpdata/en/f5/04898047bd11d2bf750000e8a7386f/frameset.htm
    I hope this will help you,
    Regards,
    Murali.

  • How to build a array with high sampling rates 1K

    Hi All:
    Now I am trying to develop a project with CRio.
    But I am not sure how to build a array with high sampling rates signal, like >1K. (Sigle-point data)
    Before, I would like to use "Build Arrary" and "Shift Register" to build a arrary, but I found it is not working for high sampling rates.
    Is there anyother good way to build a data arrary for high sampling rates??
    Thanks
    Attachments:
    Building_Array_high_rates.JPG ‏120 KB

    Can't give a sample of the FPGA right now but here is a sample bit of RT code I recently used. I am acquiring data at 51,200 samples every second. I put the data in a FIFO on the FPGA side, then I read from that FIFO on the RT side and insert the data into a pre-initialized array using "Replace Array subset" NOT "Insert into array". I keep a count of the data I have read/inserted, and once I am at 51,200 samples, I know I have 1 full second of data. At this point, I add it to a queue which sends it to another loop to be processed. Also, I don't use the new index terminal in my subVI because I know I am always adding 6400 elements so I can just multiply my counter by 6400, but if you use the method described further down below , you will want to use the "new index" to return a value because you may not always read the same number of elements using that method.
    The reason I use a timeout of 0 and a wait until next ms multiple is because if you use a timeout wired to the FIFO read node, it spins a loop in the background that polls for data, which rails your processor. Depending on what type of acquisition you are doing, you can also use the method of reading 0 elements, then using the "elements remaining" variable, to wire up another node as is shown below. This was not an option for me because of my programs architecture and needing chunks of 1 second data. Had I used this method it would have overcomplicated things if I read more elements then I had available in my 51,200 buffer.
    Let me knwo if you have more qeustions
    CLA, LabVIEW Versions 2010-2013
    Attachments:
    RT.PNG ‏36 KB
    FIFO read.PNG ‏4 KB

  • How to create a field with  1200 chars length

    Hi,
    Will anybody let me know how to create a field with length 1200 in a table.
    Regards,
    Madhavi

    Hi Madhvi,
    Other thing what you can do is
    1. First create a Table type.
         Goto SE11-> Dataelements ->Table type
         There on the next screen select Predefine radio button & there provide data type & size.
    2. Create a structure having a field typa of Table type created before. say that field is quant.
    Now in your program refer that structure to create an internal table & work area.
    Now if u append ur text to the field quant.
    try creating line type of size more that 255 if it works then fine other wise reduce it.
    Note:: This will be a deep structure.
    so first append value to the field quant,  the at the end of first record append valu to ur internal table.
    thanks
    Satyam

Maybe you are looking for

  • How do I complain about a store?

    So for three years in a row, the apple store at the Grand Arcade in Cambridge, England, has made my itouch worse and worse. Three years ago when my itouch was still under waranty, it froze for no reason (as my previous ipods did, but they lost warran

  • Audio in flash

    Hello all, i am new to the forum and find it very helpful, however i have a problem that i have not found a solution for. I am making a flash "slide" presentation using flash mx. I would like to have audio for each frame, explaining what is on the fr

  • BEx Analyzer workbook working strangely with reset_area functionality

    Hi Experts, In my BEx Analyzer I have got an input ready query for planning. It displays data correctly. In my workbook I have a button for variables, a button to save the data to planned cube and a button for reset. For the reset button i have used

  • Getting an Error WIJ20002 while trying to create a webi report in infoview

    Hi, We are getting an error " The Webintelligence Report Panel cannot connect to the server.Close the report panel and try to connect again or see your Business Objects Administrator ( WIJ20002)" only for a single universe. Please suggest how can we

  • Tables in dba_objects view not present in dba_all_tables view

    I have found tables in view dba_objects (object_type='TABLE'), which I haven't found in dba_tables, or dba_all_tables views. What kind of tables are they? E.g. in mdsys schema: select object_name,object_type from dba_objects where owner='MDSYS' and o