Initializing an array of generics

Hello all,
I have declared an array of Vector with generics. The declaration is OK but the initialization gives me an error.
This is the declaration
Vector<Integer>[] x;This must be an array. Each element of the array is of type Vector<Integer>.
I tried to initialize it using the line
x = new Vector<Integer>[4];but it didn't work.
I also tried
x = new Vector[4]<Integer>;but didn't work also. The only initialization that worked is
x = new Vector[4];But I want to put the generic tag in the initialization because it gives me warning.
Any suggestions?
Regards,
Ahmed Saad

x = new <Integer> Vector[4];When I compile that with Sun's javac compiler, I
still get a warning.
If you are not, it's a bug in the compiler you are
using.
As far as I know, the code above is no different
from:
x = new  Vector[4];
yeah, I am trying to solve the same problem, and despite the person posting it worked, it didn't get rid of the problem for me...
private Vector<Object> [] data;
X.java:nn: generic array creation
this.data = new Vector<Object>[2];
X.java:nn: warning: [unchecked] unchecked conversion
found : java.util.Vector[]
required: java.util.Vector<java.lang.Object>[]
this.data = new Vector[2];
X.java:nn: warning: [unchecked] unchecked conversion
found : java.util.Vector[]
required: java.util.Vector<java.lang.Object>[]
this.data = new <Object>Vector[2];
^

Similar Messages

  • Array of generic class

    Hi.
    i have to create an array of generic class
    ex: GenericClass<E> [ ] x = new GenericClass<E>[ y ]
    is it possible?
    i can create GenericClass<E> [ ] x; but i can't initiate it in this way..
    Someone know how i can do it?

    crosspost
    http://forum.java.sun.com/thread.jspa?threadID=746524&messageID=4272614#4272614

  • 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.

  • Initializing object array

    Hi,
    I am having problem initializing object array - here is my scenario -
    I have created class a -
    public class A {
    Public String a1;
    Public String a2;
    Public String a3;
    }the I have created class b
    public class B {
    Public A [] aa;
    }and I want to initialiaze my class bi in anoither clas c
    public class C{
    A ar = new A;
    ar.aa[0].a1 = "test"
    }this gives me null ..please anybody help me
    Neha
    }

    Thanks for the reply ..I know this is not good code ..but I have to write the classes in this way in SAP to create the Webservice ...the SAP side understand this type of structure only ..I still got the same error ..here are my original classes -
    public class GRDataItem {
         public String AUFNR ;
         public String EXIDP ;
         public String EXIDC;
         public String MATNR ;
         public String WERKS ;
         public String CHARG ;
         public String VEMNG ;
         public String VEMEH ;
         public String CWMVEMEH ;
         public String CWMVEMNG ;
         public String STATUS;
    public class GRDataTab {
         public GRDataItem [] grItem;
    Public class webservice {
                int sn = 20 ;
                  GRDataTab tab = new GRDataTab();
                tab.grItem = new GRDataItem[sn];
                tab.grItem[1].AUFNR = "12";
    }Thanks for all your help
    Neha

  • Array of generics (JLS seems too restrictive)

    Hi everybody,
    with some friends (in a lab) we currently develop a compiler generator
    (a la SableCC i.e SLR, LR, LALR).
    Because we start last june, we develop using jdk 1.5 and
    generics. For me, i think it save us lot of time mainly because
    Map<NonTerminal,Map<LRItem,Node>> is more readable
    than Map :)
    And this is my question : why CREATION of array of generics is unsafe ?
    I don't understand why a code like below is tagged unsafe :
    HashMap<State,Action>[] maps=new HashMap<State,Action>[5];
    for(int i=0;i<map.length;i++)
      maps=new HashMap<State,Action>();
    For me, the fact that JLS forbids array of generics creation
    is too restrictive, only cases where type parameter are lost
    should be tagged as unsafe.
    Example :
    Object[] array=maps; // unsafe
    Object o=map;            // weird but unsafe because
                                          // Object[] o=(Object[])(Object)maps; must be unsafeWhat do you think about this ?
    R�mi Forax

    The question is why :
    Future<Double>[] futures=new
    Future<Double>[10000];
    is not allowed. It seems safe !First of all, it would not be safe. The example below would exhibit exactly the same vulnerabilities with this assignment as it would with any of the allowed ones. This is because both the declared type and the runtime type would still be the same.
    It seems the current implementation is not able to detect (and warn about) the unsafety of the assignment above. That's why you're not allowed to use it: allowing it would provide a very false sense of type-safety
    and why :
    Object[] o=futures;
    is not tagged unsafe.
    It's unsafe because you can write :
    Object[] o=futures;
    o[0]=new Future<String>(); // for the example, let
    says Future is a class
    R�mi ForaxThis is probably done to avoid redundancy. As far as I can see, in all cases where this could be unsafe, you have been notified about the lack of safety already when you first assigned to futures.

  • Initializing string array registers

    Hello. I have posted my project. It is not even close to finished but I am having trouble initializing the array's labeled "Up values" and "Down values", to "0" for all elements, at beginning of Vi run. So, when I am at the Front Panel and running the Vi, I would like all of the fields to begin with a "0", the moment the Vi is started. I have tried a couple different things I could think of and watched the Core 1 Video about arrays again however, it doesn't give the example for a string and nothing I have tried so far, is working. Thank you.

    crossrulz wrote:
    There are a few options to you:
    1. Use an initialization state to write to your indicators their default values via a local variable
    2. Put the default values into the indicators and then right-click on them and choose Data Operations->Make Current Value Default.  This will store the default value in the indicators themselves.
    I would recommend going with #1.
    2. Put the default values into the indicators and then right-click on them and choose Data Operations->Make Current Value Default.  This will store the default value in the indicators themselves. I put a "0" in each field, I slected "make current value default, but after the Vi ran, and then I started the Vi again, it keeps the numbers in the registers that are left over from the previous test. I also tried your suggestion #1. however, it still isn't writing a "0" in all the fields. The reason for this is that I don't want the operator's to read old data accidentally, when the Vi is running. I thought if I wipe all the registers out, it will prevent that from happening.

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

  • Initializing an array of clusters in a CIN?

    I'm trying to write a CIN to connect to a mySQL database, retreive some information, and return it to labVIEW for display. The connection works perfectly using ODBC, but I'm having major trouble getting the information back to LabVIEW. I'm new to CINs and I'm still slightly confused as to how the different structures work. I want to return the data in an array of clusters (using struct names, a 'Set' of 'Records'). LV generated the structs, and I simply renamed some of the fields/names. The code I have so far works up to the point specified in the source below, when I try to initialize the array for data entry. I think what's throwing me off is the conplexity of my structures. Since it's an array of clusters, and not an array of say strings or integers, I'm getting confused. If anyone could help me out by telling me what's wrong with my code, and/or filling in the section of the while loop I'm rather clueless on.
    typedef struct {
    LStrHandle Number;
    LStrHandle SerialNumber;
    } Record;
    typedef struct {
    int32 dimSize;
    Record ptr[1];
    } Set;
    typedef Set **SetHdl;
    MgErr CINRun(COpt *ConnectionOptions, LStrHandle *Number, SetHdl *RecordSet);
    MgErr CINRun(COpt *ConnectionOptions, LStrHandle *Number, SetHdl *RecordSet)
    // LV error code
    MgErr err = noErr;
    // ODBC environment variables
    HENV env = NULL;
    HDBC dbc = NULL;
    HSTMT stmt = NULL;
    // Connection options data variables
    UCHAR* dsn = malloc(SQL_MAX_DSN_LENGTH * sizeof(UCHAR));
    UCHAR* user = malloc(32 * sizeof(UCHAR));
    UCHAR* pass = malloc(32 * sizeof(UCHAR));
    UCHAR* num = malloc(16 * sizeof(UCHAR));
    // Query variables
    INT qlen;
    INT nlen;
    UCHAR colNumber[5];
    SDWORD colNumberSize;
    UCHAR* query;
    INT numRows;
    // ODBC return code storage
    RETCODE retcode;
    /** Prepare data from LV for C++ manipulation **/
    strcpy(dsn, LStrBuf((LStrPtr)(*(ConnectionOptions->DSN))));
    dsn[(*(ConnectionOptions->DSN))->cnt] = '\0';
    strcpy(user, LStrBuf((LStrPtr)(*(ConnectionOptions->Username))));
    user[(*(ConnectionOptions->Username))->cnt] = '\0';
    strcpy(pass, LStrBuf((LStrPtr)(*(ConnectionOptions->Password))));
    pass[(*(ConnectionOptions->Password))->cnt] = '\0';
    strcpy(num, LStrBuf((LStrPtr)(*Number)));
    // Program crashes here too, but that's the least of my concerns right now. Keep reading down.
    //num[(**Number)->cnt] = '\0';
    qlen = (int)strlen(
    "SELECT m.Number FROM master AS m WHERE (m.Number LIKE '');"
    nlen = (int)strlen(num);
    query = malloc((qlen + nlen + 1) * sizeof(UCHAR));
    sprintf(query,
    "SELECT m.Number FROM master AS m WHERE (m.Number LIKE '%s'\0);",
    num);
    // Prepare and make connection to database
    SQLAllocEnv (&env);
    SQLAllocConnect(env, &dbc);
    retcode = SQLConnect(dbc, dsn, SQL_NTS, user, SQL_NTS, pass, SQL_NTS);
    // Test success of connection
    if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
    retcode = SQLAllocStmt(dbc, stmt);
    retcode = SQLPrepare(stmt, query, sizeof(query));
    retcode = SQLExecute(stmt);
    SQLBindCol(stmt, 1, SQL_C_CHAR, colNumber, sizeof(colNumber), &colNumberSize);
    SQLRowCount(stmt, &numRows);
    //Program crashes on the following line. I get an error in LV saying something about an error in memory.cpp
    DSSetHandleSize((*RecordSet), sizeof(int32) + (numRows * sizeof(Record)));
    (**RecordSet)->dimSize = numRows;
    retcode = SQLFetch(stmt);
    numRows = 0;
    while (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
    /* Need code here to retreive/create Records and put them in the array */
    retcode = SQLFetch(stmt);
    numRows++;
    SQLDisconnect(dbc);
    else
    // Free ODBC environment variables
    SQLFreeConnect(dbc);
    SQLFreeEnv(env);
    // Return LV error code
    return err;

    This looks incorrect:
    MgErr CINRun(COpt *ConnectionOptions, LStrHandle *Number, SetHdl *RecordSet)
    Did you let LabVIEW generate the C file??
    When you pass an array of clusters to a CIN, what is passed is a handle to the array. You are declaring a pointer to a handle. I just did a test passing an array of clusters to a CIN. The C file looks like this (comments are mine):
    typedef struct {
    int32 Num1;
    int32 Num2;
    } TD2; // the cluster
    typeDef struct {
    int32 dimSize;
    TD2 Cluster[1];
    } TD1; // the array
    typeDef TD1 **TD1Hdl; // handle to the array
    CIN MgErr CINRun(TD1Hdl Array);
    Notice that it passes you a HANDLE, not a pointer to a handle.
    On this line:
    DSSetHandleSize((*RecordSet), sizeof(int32) + (numRows * sizeof(Record)));
    If RecordSet is a HANDLE, then (*RecordSet) is a POINTER - you are passing a POINTER to a routine that expects a HANDLE.
    The line:
    (**RecordSet)->dimSize = numRows;
    Is also incorrect - if RecordSet is a HANDLE, then (*RecordSet) is a POINTER, and (**RecordSet) is an ARRAY, but you're asking it to be a pointer. (*RecordSet)->dimSize would be the size to fetch.
    Read the rules again on what is passed to CINs.
    I strongly suggest developing the interface first - the VI that calls the CIN. Put the CIN in place and let LabVIEW generate the initial C file.
    Then modify the code to do something simple with the input arguments, like fetch the array size, and put this number into an output argument. Something VERY basic, just to test the ins and outs. Debug this until all ins and outs are working.
    THEN AND ONLY THEN add code to do whatever work needs doing.
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

  • Creating array of generic object

    hello, what i want to do is something like:
    public class AClass<K extends SomeObject>{
        SomeObject[] AnArray;
        public void amethod() {
            AnArray=new K[10];
    }So I want to create an array of some kind of object at runtime without already know the kind of the object. The thing is that I think that generics are only "known" at compiling time, so this AnArray=new K[10]; is propably completely wrong but I cannot think of any other way of creating an array without knowing in advance the kind of object....So if someone could enlighten me on how to do this...
    if this is of any help the reason i want to have such implementation is that this array is supposed to be a hashmap and the SomeObject is supposed to be a super class of some different kind of LinkedList classes, so I want the hashmap to be flexible on what kind of list will be used. Suggestions for completely different approach are also welcome offcourse, but I would prefer it if someone could give some brief explaination on how manipulating such a generic array issue...

    Hi Fraksia,
    Unfortunately, array creation of type parameters is not allowed, so you can't
    say new T[3]; That is because T doesn't exist at compile time. It is erased.
    It is misleading - I know. Because when you say
    AClass<SomeObject> aclass=new AClass<SomeObject>();you might thing that T becomes SomeObject in your class wheres
    what that does is that whenever you expect your type parameter in
    the calling code, compiler will insert a cast. See the example below:
    class MyClass<T> {
       T o;
       public MyClass(T o) {
          this.o=o;
       public T get() {
          return o;
    class CallingClass {
       public static void main(String[] args) {
          MyClass<String> m=new MyClass<String>("Test");
          String o=m.get();  //no cast needed here
    }Benefit: increased type safety, no casts needed in the CallingClass.
    What really happens is:
    class MyClass {
       Object o;
       public MyClass(Object o) {
          this.o=o;
       public Object get() {
          return o;
    class CallingClass {
       public static void main(String[] args) {
          MyClass m=new MyClass("Test);
          String s=(String)m.get();  // compiler inserts cast here based on your type parameter
    }That is why you can't do what you wanted - because "there is no spoon" ;)
    Generics in Java are only a compile time feature.
    Cheers,
    Adrian

  • Initializing an array question

    if i wanted to initialize elements of an array and get input from the user of how many there will be. where can i find some info on this?
    basically instead of initializing 0,1,2,3, and so on i wanted to do it in a for loop, but i have tried it a couple of different ways with no luck.
    maybe you guys can give me some insight on how i need to set this thing up or what i need to think about or where some of the reading is?
    any info would help
    thanks in advance guys

    well here is the code for it i thought i was intializing it correctly??
    public static void main(String[] args) {
            int y;
            int x;
            int maxValue = 0;
            int numRepitions;
            int [] counters = new int[maxValue];
            Scanner keyin = new Scanner(System.in);
            Random generator = new Random();
                System.out.println("please enter how many random numbers you would like to generate");
                maxValue = keyin.nextInt();
                System.out.println("please eneter how many values your would like to draw for");
                numRepitions = keyin.nextInt();
                for(y = numRepitions - 1; y >= 0; y--)
                   counters[y] = numRepitions;
                   counters[numRepitions]--;
           

  • Initializing an array

    I have an array that needs to be initialized 1096 times, I
    don't want to use a cfloop because I am looking for a better
    performance. So I use a query that brings all the records that have
    been initialized, the problem is if some of them hasn't been
    initialized and I use some conditionals as CFIF the application
    will throw an error because the specified position into the array
    doesn't exist yet.
    Here's my code.
    <cfquery name="lista_espacios"
    datasource="#Application.BD#">
    SELECT ISNULL(id_espacio,0) as id_espacio, ruta, url, alt
    FROM ESPACIOS
    ORDER BY id_espacio
    </cfquery>
    <cfloop query="lista_espacios">
    <cfset lista[lista_espacios.id_espacio][1] =
    lista_espacios.id_espacio>
    <cfset lista[lista_espacios.id_espacio][2] =
    lista_espacios.ruta>
    <cfset lista[lista_espacios.id_espacio][3] =
    lista_espacios.url>
    <cfset lista[lista_espacios.id_espacio][4] =
    lista_espacios.alt>
    </cfloop>
    <cfset cont=1>
    <cfif #lista[cont][1]# EQ #cont# ><a
    href="#lista[cont][3]#" onclick="abrirURL(#lista[cont][1]#);"
    target="_blank"><img style="border:0px" width="13"
    height="13" src="#lista[cont][2]#" title="#lista[cont][4]#"
    alt="#lista[cont][4]#" />
    </a>
    <cfelse>
    <img width="13" height="13" src="img/bad.jpg" />
    </cfif>
    <cfset cont = #cont#+1>

    quote:
    Originally posted by:
    Newsgroup User
    If I understand your requirements you have a database that
    has some
    records, but not necessarily all 1096 records at this time.
    You want to
    pull out these records, but have a full set of 1096 records
    even if some
    of them do not yet exist in the dataset.
    There are database tricks that can be used to create a record
    set like
    this. Hopefully somebody will chime in with the details. This
    would
    greatly simplify your processing after that.
    There is not enough information to know what approach would
    be most appropriate.
    What is the database type? Also, do the existing records have
    sequential values for idespacio, starting with 1?

  • Methodology Question: Initializing Static Arrays

    After almost gnawing my arm off in frustration, I finally stumbled onto how to go about initializing and populating a static array that's outside of my Class's constructor (by placing it inside of a static block). My problem is, I just don't understand why I needed to do it that way. My code started out as such:
    public class Parameter {
         private static appEnvironmentBean[] appEnvironment = new appEnvironmentBean[8];
         appEnvironment[0].setMachineIP("192.168.1.100")
    }and this kept throwing an error " ']' expected at line ###"
    so I changed it to this:
    public class Parameter {
         private static appEnvironmentBean[] appEnvironment = new appEnvironmentBean[8];
         static {
         appEnvironment[0].setMachineIP("192.168.1.100")
    }and it worked. Now my problem is, I'm assigning a literal, and I declared the Bean array as static, so the way I see it, there was no reason to throw assignments to the array inside of a static block. I'll take it as a "That's just the way it is" thing, but if someone out there could explain the reasoning behind having to put my assignments inside of a static block, it would really be appreciated.
    Thanks!

    Because if you didn't put it inside a static block you'd be attempting to execute code outside of a method which is illegal except for initialization.
    I think you could do it this way:
    private static appEnvironmentBean[] appEnvironment = {
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100") };it depends on whether setMachineIP returns an appEnvironmentBean.

  • Stalling a form from loading until the initial javascript arrays are loaded

    I am looking for a way to get a form to be hidden based on the onload event. I would like to call a javascript function to initially populate some select boxes based on javascript arrays, but I would like this to happen before the page loads or at least stall displaying the select boxes until they are populated.
    The way it is setup now, when the page loads, the select boxes try to load first and then the rest of the form loads. I would like to know if there is a way to load the select boxes from the javascript arrays, then have the select boxes and other form elements show up at the same time. I have tried putting a <div> around the entire form and within the javascript populate function I first use "document.formname.div_id.style.visibility=hidden" then at the end of the select box population within the function, I use "document.formname.div_id.style.visiblity=visible". I tried this and the select boxes appear blank; it is as if the populate function doesn't work at all.
    I realize this is a very long question, but I will award you Duke Dollars if you help me out!!!

    right now, I have it set up where I click on a link which is a jsp page which forwards me to the jsp page that has all the html in it. That page is where I initially try to populate the select boxes with the javscript arrays...I also have a number of javascript functions which change the contents of the select boxes based on another select box in the form. Will i have access to those "java" arrays, [instead of using the javascript arrays], that you are suggesting in the javascript code? I do need to use whatever arrays I create in javascript functions.

  • Initializing a array of elements

    long[] ids
    want to initialize ids to 0
    how to do that??
    Thanks.

    getting compilation error that array might not have
    been initialized.Then your code didn't necessarily create an array. You probably have something like this:
    long[] ids; <-- not assigned (yet)
    if (condition1) {
    ids = new long[42]; <-- assigned here, but conditionally
    ids[0] = 0; <-- oops - ids might not have even been initialized at all!

  • Initializing an array of 13 button objects - a more compact way?

    This works, but I was wondering if there was a more compact syntax for what I am doing.
    I'm creating an array that contains 13 UIButton objects as follows:
    NSArray * myButtonObjects;
    myButtonObjects = [NSArray arrayWithObjects: [UIButton buttonWithType:UIButtonTypeRoundedRect],
    [UIButton buttonWithType:UIButtonTypeRoundedRect], [UIButton buttonWithType:UIButtonTypeRoundedRect],
    [UIButton buttonWithType:UIButtonTypeRoundedRect], [UIButton buttonWithType:UIButtonTypeRoundedRect],
    [UIButton buttonWithType:UIButtonTypeRoundedRect], [UIButton buttonWithType:UIButtonTypeRoundedRect],
    [UIButton buttonWithType:UIButtonTypeRoundedRect], [UIButton buttonWithType:UIButtonTypeRoundedRect],
    [UIButton buttonWithType:UIButtonTypeRoundedRect], [UIButton buttonWithType:UIButtonTypeRoundedRect],
    [UIButton buttonWithType:UIButtonTypeRoundedRect], [UIButton buttonWithType:UIButtonTypeRoundedRect], nil];
    Is there a shorter way of doing this, like specifying the number of UIButton objects I want to create the NSArray with?
    Thanks,
    doug

    Since my first long statement where I repeated the UIButton object 13 times worked, I thought this would work as well:
    NSArray *theButtons;
    for (i=0; i<13; i++) {
    [theButtons arrayByAddingObject:[UIButton buttonWithType:UIButtonTypeRoundedRect]];
    That compiles, but it doesn't work like the original. The program crashes when it tries to run that loop.
    doug

Maybe you are looking for

  • All in one Printer hp psc 1410

    I am having problems printing online. I have done a Printer Test Page which was successful. When I try to print, it goes to the printer page and then it goes away as if something is blocking it. I have just installed Norton Interner security. Could t

  • Mail Queue filling up with DSN failures

    So my Exchange 2010 queue viewer keeps filling up with failed DSNs. There is no sender (except for [email protected]). I have done some searching and the first thing that everyone usually mentions as a cause is SPAM. It's not SPAM.  I know this for t

  • Adding SharePoint App Workflow to On Premises Host Web Site from App Web

    Hi, Is there a way to add (associate after deploying) a SharePoint 2013 App workflow to Host Web ONPREMISES. I see most of the posts suggests it is not possible ONPREMISES and only available in SharePoint Online. Below is a link which says it is poss

  • Will iBooks ever support Adobe DRM?

    I quite often want to read books that are not available in the UK iBookstore. These books are almost always available from another UK publisher in ePub format, but with Adobe DRM. So I now use another ebook reader app that supports Adobe DRM. The oth

  • Appleworks database to windows programs

    I have a AW database file that I use for creating mailing labels. I am no longer the person in charge of doing the labels or mailing. Can I translate my AW file to something that can be used by several different windows apps for creating labels. Part