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.

Similar Messages

  • 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());
    }

  • How to create an array using reflection.

    How to create an array using reflection.
    I want to achive something like this,Object o;
    o = (Object)(new TestClass[10]);but by use of reflection.
    To create a single object is simple:Object o;
    o = Class.forName("TestClass").newInstance();But how do I create an array of objects, when the class of objects is known only by name? (Can't use Object[] because even though an Object[] array can be filled with "TestClass" elements only, it Cannot be casted to a TestClass[] array)
    Anybody knows?":-)
    Ragnvald Barth
    Software enigneer

    Found it!
    the java.lang.reflect.Array class solves it!
    Yes !!!

  • How to create an array of linklists??? ... plz

    Hi guys,
    I am trying to create a Hash table. My link list is already working. But i am still confused about how to create any array linklist for solving the collisions. Do i need to create a new instance of the linklist for each array slot? What is the better way to do?
    just need some hint to start it.
    abdul

    Yes, you need to create a new instace for each slot.
    LinkedList[] ht = new LinkedList[size];
    for(int x = 0; x < size; x++)
        ht[x] = new LinkedList();

  • How to create an array variable

    Hi folks,
    I'm developing a flowN activity , for each branch created, I need to pass different values (values I get from DB).
    For this my plan would be,
    -create an array variable , load all the values(from DB) into the array
    -pass the array to each branch in flowN activity based on the index
    As I'm newbie to BPEL, I do not know how to create an array variable.
    Could you people guide me please.
    Regards
    Viki

    Hi,
    I created my string array like
    <element name="string_array">
    <complexType>
    <sequence>
    <element name="input" type="string" minOccurs="0" maxOccurs="unbounded"/>
    </sequence>
    </complexType>
    </element>
    <variable name="arr" element="client:string_array"/>
    I am able to add values to my array variable named as "arr"
    When I use the following code snippet, it gives my the value of the entire list.
    <%ora:getNodeValue(bpws:getVariableData('arr'))%>
    But when I try retireve values one by one like <%ora:getElement('arr','/client:string_array/client:input',[0])%>, its giving me error.
    Guide to get throu' this.
    Viki

  • 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 ArrayLists?

    Hello,
    I'm trying to compile the following code:
    ArrayList<Object> arr[];
    arr = new ArrayList<Object>()[size];in order to create an array of ArrayLists. I'm being met with the following compilation error:
    The type of this expression must be an array type but it resolved to ArrayList<Object>
    Can anyone show me how to correctly do this?
    Thanks

    {color:#3D2B1F}This line:
    List<Object>[] arr = new ArrayList<Object>[5];generates the compiler error: "generic array creation" (generics and arrays don't play well together)
    Since you are just parameterizing with Object, you can use non-generic collections:
    List[] arr = new ArrayList[5];Me? I don't like mixing arrays and collections. I would have a list of lists:
    List<List<X>> matrix = new ArrayList<List<X>>();{color}

  • How to create an array in if/else or case structure without 0's ?

    Hello,
    I've been trying to do this for a while now.
    I only managed to think of this in three ways:
    1. (What I'm doing right now Create the array by going through a for loop, which populates the array by auto indexing. It populates with correct number if true and with a '0' if false. The idea was to delete the 0's later on in the code. This however seems highly ineffective.
    2. Make use of a shift register, which automatically adds the correct number to an array. The problem is that the array will keep growing and growing and at the very least would tremendously slow down my program. At worst, it would crash.
    So, my question is: How do I create an array that if a comparison is true, it puts the element in and if not it does nothing ?
    I've attached a PNG snippet of my code.
    Kind Regards,
    David.
    Solved!
    Go to Solution.
    Attachments:
    Get_Indices.png ‏24 KB

    Pladio wrote:
    I've been trying to do this for a while now.
    You did not explain what "this" is. Can you give some typical inputs and expected outputs? Populate your controls and indicators with typical data and make it the default efore attaching.
    Pladio wrote:
    So, my question is: How do I create an array that if a comparison is true, it puts the element in and if not it does nothing ?
    Your code show three different comparisons. Which one are you talking about.
    Pladio wrote:
    I've attached a PNG snippet of my code.
    That code makes very little sense. Why is there a shift register if the data in it never changes? What is the purpose of the inner FOR loop? Why are you creating a 2D array?
    Do you want to remove all rows where the corersponding SD is zero, for example?
    LabVIEW Champion . Do more with less code and in less time .

  • How to create an array in bpel?

    I am trying to integrate a web service into open-esb. The web service consumes an unbounded array of a "userInfo" data structure. The issue is that although I can create bpel to receive a message like this, due to type incompatibilities I need to create a different array within bpel to pass to the webservice.
    To date I have not found a way to create an array within open-esb's bpel. After extensive googling I have found that other ESBs define their own proprietary extensions to add nodes to an array.
    Thus I have two questions:
    First, does open-esb support creation of arrays? and if so, how do I create the array and add nodes to it?
    Second, and perhaps more importantly, is using an <assign> activity the best way to transfer a potentially large array from one variable to another (i.e., will it perform well)? Or should I use XSLT to transform the array from one wsdl type to another? And if XSLT is the answer, how can I do this within open-esb?
    Thanks in advance,
    Steve
    PS. Based on the various googlings Ive been doing this question seems to be frequently asked. If someone will help me find a solution I plan on writing a short "how-to" article for posting back to the community. Given that arrays are one of the most basic data structures I hope the article will be useful for others struggling with this issue.

    I think this is all covered in Steve-Nies other thread concerning this subject, entitled "Need help with BPEL please" (http://forum.java.sun.com/thread.jspa?threadID=5116270&tstart=0)

  • How to create Componet array in NetBean?

    I want to create ten or more text field with same format.
    Also want to use NetBean to done it with out typing the code self.
    How can I do?
    I mean whether easy and fast method to create componet array in netbean.

    I want to create ten or more text field with same
    format.
    Also want to use NetBean to done it with out typing
    the code self.Why not? because it's the fastest, simplest and safest way.
    How can I do?
    I mean whether easy and fast method to create
    componet array in netbean.Just like oyu'd do it without Netbeans.
    If you still want to do it in Netbeans, I suggest reading the manual. This is not a Netbeans product support forum, and I'm definitely not inclined to help as you don't want it done by writing code yourself.

  • How to create an array of Vectors ?

    Can I create an array of vectors in Java ? For instance I want to have an array of days in a year, an on each day there are several things to do, and I don't know this up front, so I want it to be a Vector holding the things_to_do object, some days might have nothing to do, so there should be null or an empty vector for that day. So I came up with something like the following :
    Vector<Things>[] Days_Array=new Vector<Things>[365];
    But Java doesn't allow this ?
    Frank

    Opps , I forgot to ask, although it compiled successfully, but it gave me a warning : [unchecked] unchecked conversion
    I wonder if there is a way to fix it without turning the warning off, what I meant is : Am I missing something that caused the warning that I should add to the code, I don't want to turn off the warning. For instance how can I make the "conversion" checked ?
    Frank

  • 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 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 an array list of strings by using buttons?

    HI, i need some guidance from you guys to help me out. How do i create a list of array whenever i click on a button it will generate a string and place it in an array row by row. if i dont click on the button it will ignore it and wont create the array. i have tried many technics such as looping and building array but it wont generate the list that i want.
    Attachments:
    untitled.JPG ‏97 KB

    I am not sure if I have understood your question correctly, but is the attached what you were looking for?
    Adnan Zafar
    Certified LabVIEW Architect
    Coleman Technologies
    Attachments:
    Example.vi ‏12 KB
    example.JPG ‏100 KB

  • How to create an array containing shared variable values

    Hi
    I am trying to programmatically create an array containing shared variable values and their names.  I can get the variable names by supplying the process name to the get shared variable list function.  How do I then read the value of all the shared variable items returned?
    I have used a data socket open to open a connection to all variables when my program starts.  I then use datasocket read on the opened connections to write to an array.  This works fine until I try to write to one of the variables using a shared variable node.  The variables writes can take from 4secs to 2 mins.  When I remove the shared variable node again all is fine.  Also when I stop using the data sockets, all is fine.
    Is there a conflict between shared variable nodes and data socket writes to the shared variables?
    Can anyone help?  I cannot easily post example code because I am reading the variables from a Wago PFC (PLC) using OPC.

    Hi
    Sorry I forgot to mention the LabVIEW version, its 8.20.  I have tried saving the shared variable node as a sub VI and it makes no difference.
    Attached is a stripped down version of the software.  You will not be able to connect to the IO server because it requires some Wago hardware and software.  You may spot something I have done wrong with the I/O servers, variables or sub VI's.
    The main program that runs is called 'HMI Engine' in the 'Framework' folder.  There may be some other things in the project that aren't used in this example.  I have removed all but the variable connection part of the code.
    I hope someone can help!?
    Thanks
    Mark.
    Attachments:
    HMI Test.zip ‏144 KB

Maybe you are looking for

  • Error while confgiuring Siebel Bi Publisher Security Model..

    Hi, Steps Done 1)     Imported the BIPSiebelSecurityWS.XML 2)     Replaced Existing address with the specific address of the Siebel Server 3)     Enabled Local Super user checkbox, entered a Super user name and password 4)     Configured the Siebel S

  • How to find out if Adobe products bought "as is" in an auction have been activated? [was: license]

    Hello everybody out there, we're an IT business. We've bought several Adobe products in an auction. As the products are sold "as is", we don't know if they've been activated or not. We've bought those products in order to resell them. Does someone kn

  • Due date checking in F110

    Hi, My client want to use F110(Automatic outgoing Payment) to payment the vendors. But they want to avail Credit for at least 30 days .that means , those invoice process had been done before 30 days those should come to the APP PROPOSAL FOR THE PARTI

  • Lost my ipod nano 3rd gen

    Yeah i lost my ipod and i was wondering if it could be tracked please help me.

  • Shopping Cart workflow error

    Hi, We have just started with the setting up of the SRM 5.0 system. Scenario is Classic. we have activated the Shopping Cart without approval WF, however, when a SHC is created the system shows the status of SHC in Approval. Dont know what i have mis