Create a unlimited object array.

I need to be able to create an Object array of unlimited or extended size. I don't know how many of the objects I'm going to need when the program starts. I need the ability to alocate more space as needed. How can I do this. Please show a small example. Thanks.
Matt S.

Yes. You might need to cast the Object coming out of the List to whatever type you put in there. See the API docs for ArrayList. Depending on your needs you might want to use a Map or Set or Tree, look at the java.util classes that implement those interfaces and see what meets your needs.
Lee

Similar Messages

  • Empty Object Array

    Hi,
    How can I create an empty object array in Java?
    Thanks
    g

    Object object[] = new Object[len]; //len is an
    Integer-value for the length of the arrayThat's right..

  • Java object array

    Hi all,
    first of all let's see some lines of source code
    Foo.java
    public class Foo
    public Socket pSocket = null;
    public nPosition = 0;
    NewBie.java
    public class NewBie{
    public Foo[] m_Foo = null;
    private int m_FooCount ;
    public Init(int nFooCount)
    m_Foo = new Foo[nFooCount];
    m_FooCount = nFooCount;
    public Operate()
    int i = 0;
    for( i= 0; i< m_FooCount; i++)
    //follwing line will throw a exception
    m_Foo.pSocket..... //Here is some operations with m_Foo[i].pSocket
    Funny.java
    public class Funny
    public static NewBie m_pNewBie = new NewBie();
    public static void main(String argv[])
    m_pNewBie.Init(10);
    m_pNewBie.Operate();
    %>java Funny
    Failed I/O:java.lang.NullPointerException
    when I debug the program , seems m_Foo[i].pSocket in method Operate of NewBie object is null. I am puzzled, because I have created a NewBie object array with "new", why it still be null?
    Any one can give me a detailed explaination? Thanks a lot.

    Arrays contain references, not objects. You must initialize the references within the array to point to constructed objects. Otherwise, the references will be null:
    m_Foo = new Foo[nFooCount];
    // m_Foo[0] is currently null -- the reference does not point to any object
    m_Foo[0] = new Foo();
    // now m_Foo[0] points to an object so is not null

  • Can u have a spry data set Object array.....

    Ok this is what i need to do. I need a spry object array to
    be created with in a function.
    Just like this.....
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Transitional//EN" "
    http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="
    http://www.w3.org/1999/xhtml"
    xmlns:spry="
    http://ns.adobe.com/spry">
    <head>
    <meta http-equiv="Content-Type" content="text/html;
    charset=iso-8859-1" />
    <title>Hijax Demo - Notes 1</title>
    <script language="JavaScript" type="text/javascript"
    src="includes/xpath.js"></script>
    <script language="JavaScript" type="text/javascript"
    src="includes/SpryData.js"></script>
    <script language="JavaScript" type="text/javascript">
    * @author nadeerak
    function test5(){
    funObjects = new Array();
    funObjectsObserver = new Array();
    funListList = new Array();
    x = new Array();
    x[0] = "First";
    x[1] = "Second";
    x[2] = "Third";
    x[3] = "Fourth";
    for(y in x)
    funObjects[x[y]] = new
    Spry.Data.XMLDataSet("notes"+y+".xml", "notes/note");
    funObjectsObserver[x[y]] = new Object;
    funListList[x[y]] = null;
    funObjects[x[y]].useCache = false;
    funObjects[x[y]].loadData();
    funObjectsObserver[x[y]].onDataChanged = function(dataSet,
    data)
    funListList[x[y]]=funObjects[x[y]].getData();
    alert(funListList[x[y]].length);
    funObjectsObserver[x[y]].onPreLoad = function(dataSet, data)
    alert("preload");
    funObjectsObserver[x[y]].onPostLoad = function(dataSet,
    data)
    funObjects[x[y]].addObserver(funObjectsObserver[x[y]]);
    </script>
    </head>
    <body>
    <input type="button" value="button" name="button"
    onclick="test5();">
    </body>
    </html>
    i have note0.xml to note6.xml
    once the button clicked i need all the alerts to give the
    length. But this dyanimically created objects does not load. Why?
    Can we do something like this in SPY? like creating a spry
    object array........... can we?
    The error im getting is after two alerts i get
    "funListList[]. is null or not an object " individually it works
    very well?
    why is this?
    To my knowladge the data is not loaded after the second....
    Hmmmm how come? im using seperate objects....
    PLS ALL SPRY LOVERS help me......

    Hi,
    Check this sample:
    http://labs.adobe.com/technologies/spry/samples/DataSetSample.html
    Check the source code to see how we build a data set from an
    array.
    Hope this helps,
    Donald Booth
    Adobe Spry Team

  • How to create an Object array(two dimensional) from a properties file..

    Hi All..
    I have a typical problem..
    I have a properties file with key/value pairs . Now what I want to do is.. I need to read all the keys and the values corresponding to that keys and then create a two dimensional array.. Like..
    Properties props;
    Object[][] contents;
    My contents should be like
    contents = {{key1,value1},{key2,value2},{key3,value3},...};
    Can someone tell me how to do this.. asap...
    TIA
    CK

    Just because something is difficult for you does not qualify it as an "Advance Language Topic"... And it certainly doesn't allow you to multi-post.

  • VBA: problems in creating and storing objects in array with loop

    I created a Class named Issue. Then I created a function that creates Issue objects, set their properties with data from a worksheet and store them into a variant array through a loop. the problem is that everytime that the loops runs it overwrites the properties
    of the same object instead of creating a new object, setting its properties. Would anyone know how to solve that? The loop code goes below:
     'Stores all the Issues objects in an Array
    Function StoreAllIssues() As Variant
    Dim IssuesSheet As Worksheet
    Set IssuesSheet = Sheet1
    Dim intLastRow As Integer
    intLastRow = Uteis_Jorge.LastRowFunc(IssuesSheet, 1)
    Dim IssuesArray() As New Issue: ReDim IssuesArray(0)
    For i = 2 To intLastRow
        Dim MyIssue As New Issue
        MyIssue.IssueName = IssuesSheet.Cells(i, 1)
        MyIssue.Suggestion = IssuesSheet.Cells(i, 2)
        MyIssue.Priority = IssuesSheet.Cells(i, 3)
        MyIssue.Resolution = IssuesSheet.Cells(i, 4)
        MyIssue.JobStatus = IssuesSheet.Cells(i, 5)
        MyIssue.AssignedTo = IssuesSheet.Cells(i, 6)
        Set IssuesArray(i - 2) = MyIssue
        ReDim Preserve IssuesArray(i - 1)
    Next i
    ReDim Preserve IssuesArray(i - 3)
    StoreAllIssues = IssuesArray
    End Function
    Jorge Barbi Martins ([email protected])

    Hi Jorge,
    You can set the MyIssue to Nothing every time you don't use the MyIssue object, in this way, the array will properly store the new MyIssue object:
    For i = 2 To intLastRow
    Dim MyIssue As New Issue
    MyIssue.IssueName=IssuesSheet.Cells(i,1)
    Set IssuesArray(i - 2) = MyIssue
    ReDim Preserve IssuesArray(i - 1)
    Set MyIssue = Nothing
    Next i
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Creating  object array

    how to create an object array for the class ?
    which should be increment dynamically.

    i will have an separate class which has an JPanel
    with components for eg customclass .
    for that i need to create an object with array in the
    main class. which should be increment as the action
    performed.Is there a question you want to ask? You've already been given an answer to the one you asked, yet you replied with a nonsensical statement. There is no such thing as a "dynamic array" in Java. All arrays are of a fixed size. If you want a larger array you'll have to create a larger array and copy the contents of the old array to the new array. Alternatively you can use a List implementation such as ArrayList that can take care of that job for you.

  • Create Object Array

    I am trying to do a simple task that I thought would be very easy and quick to do but I have run into problems
    I am trying to get the user to input a number and based on that number make a text field to become visible based on it. So if the user input 3 the first 3 textfields would become visible. I have 10 textfields and I don't need any error handling yet as I can do that later but this is my code:
    var x=NumericField1.rawValue;
    for(var i=0; i<=x; i++)
    TextField1[i].presence="visible";
    I think my problem is creating the object array as all I did was double clicked in the library to create the textfields and the names come up as TextField1 then in the grey shaded area right beside it is the number 0. The next one is called TextField1 with 1 greyed out beside it.
    Can anyone help me out?
    Thanks

    SO IF YOU TRY IN JAVASCRIPT THIS WON'T WORK SO DO THIS IN "FORMCALC"
    i=NUMIRICFIELD.RAWVALUE;
    TextField1[i].presence="visible";
    PLEASE DO THIS IN FORMCALC &FEEDBACK ME
    [email protected]

  • Returning an Object Array

    I am unable to figure out the way in which I can return an object
    array from a cpp file to java. Is there any obvious error which you can spot in
    my CPP file?
    When I try to return a single object in the native function,
    it works fine but when I try to extend it and return an array of the object, it
    throws an error.
    Please find below the details
    h1. Java Class
    public class Flight {
    public String ID;
    public class InterfaceClass {
    private native Flight[] GetFlights();
    public static void main(String[] args)
    Flight[] objFlight = new
    InterfaceClass().GetFlights();
    System.+out+.println(objFlight[0].ID);
    static {
    System.+loadLibrary+("main");
    h1. CPP File
    JNIEXPORT jobjectArray JNICALL Java_InterfaceClass_GetFlights(JNIEnv env, jobject obj)
    //1. ACCESSING THE FLIGHT CLASS
    jclass cls_Flight = env->FindClass("LFlight;");
    //2. CONSTRUCTOR FOR FLIGHT CLASS
    jmethodID mid_Flight = env->GetMethodID(cls_Flight,"<init>", "()V");
    //3. CREATING AN OBJECT OF THE FLIGHT CLASS
    jobject objFlight = env->NewObject(cls_Flight, mid_Flight);
    //4. ACCESSING THE FLIGHT's "ID" FIELD
    jfieldID fid_ID = env->GetFieldID(cls_Flight, "ID","Ljava/lang/String;");
    //5. SETTING THE VALUE TO THE FLIGHT's "ID" FIELD
    env->SetObjectField(objFlight,fid_ID, env->NewStringUTF("ABC"));
    //6. ACCESSING THE FLIGHT ARRAY CLASS
    jclass cls_Flight_Array = env->FindClass("[LFlight;");
    if(cls_Flight_Array == NULL)
    printf("Error-1");
    //7. CREATING A NEW FLIGHT ARRAY OF SIZE 1 jobjectArray arrFlightArray = env->NewObjectArray(1,cls_Flight_Array,NULL);
    if(arrFlightArray == NULL)
    printf("Error-2");
    //8. INSERTING A FLIGHT BJECT TO THE ARRAY
    env->SetObjectArrayElement(arrFlightArray,0,objFlight);
    return arrFlightArray;
    h1. Error
    # A fatal error has been detected by the Java Runtime Environment:
    # EXCEPTION_ACCESS_VIOLATION
    (0xc0000005) at pc=0x6d9068d8, pid=1804, tid=3836
    # JRE version: 6.0_18-b07
    # Java VM: Java HotSpot(TM) Client VM (16.0-b13 mixed mode, sharing
    windows-x86
    # Problematic frame:
    # V [jvm.dll+0x1068d8]
    # An error report file with more information is saved as:
    # C:\Users\Amrish\Workspace\JNI Test\bin\hs_err_pid1804.log
    # If you would like to submit a bug report, please visit:
    http://java.sun.com/webapps/bugreport/crash.jsp
    C:\Users\Amrish\Workspace\JNI Test\bin>java -Djava.library.path=.
    InterfaceClass
    Exception in thread "main" java.lang.ArrayStoreException
    at
    InterfaceClass.GetFlights(Native Method)
    at
    InterfaceClass.main(InterfaceClass.java:6)
    C:\Users\Amrish\Workspace\JNI Test\bin>java -Djava.library.path=.
    InterfaceClass
    Exception in thread "main" java.lang.ArrayStoreException
    at
    InterfaceClass.GetFlights(Native Method)
    at
    InterfaceClass.main(InterfaceClass.java:6)
    Edited by: amrish_deep on Mar 18, 2010 7:40 PM
    Edited by: amrish_deep on Mar 18, 2010 7:40 PM

    //6. ACCESSING THE FLIGHT ARRAY CLASS
    jclass cls_Flight_Array = env->FindClass("[LFlight;");The argument to NewObjectArray is the +element+ class of the array you're about to create, not the +array+ class itself.

  • Object array - how to add items?

    Hello!
    I have little problem, how to add item to array, to get something like this:
    Object[][] someObject = {
    {"1", "2"},
    {"4","5"}
    };From this:
    Object[][] someObject = {
    {"1", "2"}
    };? Thanks in advance!

    Once you allocate an array like that, you can't
    resize it.
    Object[][] someObject = {
    {"1", "2"}
    };creates an array with size [1][2]. You can't makeit
    any larger. You can create a new Object[][]
    with the new size, copy the elements into the new
    array, then add your new objects in the newposition.
    or even better use arraylistExcept that he's using this for a JTable, so the best he could do is a Vector. Yuck. :)

  • Object array

    what do i have to do to create and object array in a class of other class. i tried to created an object of that class first and the create the array by the compiler complains that there is a problem. here is the code.
    classJTBar---------------------------------------------------
    ackage JTShapes;
    import java.awt.*;
    public class JTBar extends JTFilledRectangle{
         int height=20; int length=0;//i will use the inheritated methods
         public JTBar(){//contructor that will be called on creating object
    setHeight(20);//method of class JTRectangle
    setWidth(0);//method of class JTRectangle
         public void setLengh (int x){
              length = x;
         public void incLengh(int y){
              length = length+y;
    }//end class     
    User class
    port JTShapes.*;
    import JTUtils.*;
    import javax.swing.*;
    public class User extends JTUser{
         public void begin(){
    JTBar jtbarobject= new JTBar();
         JTBar[] arrayObj= new JTBar[8];
         String[] weekDay= {"Monday", "Tuesday", "Wednesday", "Thuersday",
         "Friday", "Saturday", "Sunday"};

    You don't have to do this:
    String[] weekDay = new String[]{"Monday", "Tuesday", "Wednesday", "Thuersday", "Friday", "Saturday", "Sunday"};
    This works fine:
    String[] weekDay= {"Monday", "Tuesday", "Wednesday", "Thuersday", "Friday", "Saturday", "Sunday"};
    What kind of Exception are you getting? I'm guessing you're getting a NullPointerException?
    Looks like you're declaring your array correctly, but you are not initializing it:
    JTBar[] arrayObj= new JTBar[8];
    for (int i = 0; i < arrayObj.length; i++) {
    arrayObj[i] = new JTBar();
    }

  • Object Array --- Collection

    Is there any way to directly convert and object Array to a Collection object. Basically i need to create a ArrayList from Object Array. The ArrayList has a constructor and also provides a method addAll() that accept Collection as parameter. So the problem becomes , how to convert Object Array to collection. As per my understanding all arrays should be essentially Collection Interface subclass.
    So why am i not able to cast?
    What is wrong in calling Object Array a sub class of Collection?
    // OrderLineItem[] is the object array that i wish to have as ArrayList
    // This code generates error -
    //"ErpOrder.java": Error #: 364 : cannot cast gal.ERP.OrderLineItem[] to java.util.Collection
      public void setLineItems( OrderLineItem[] arrOrderLineItem ) {
        m_arrLineItems = new ArrayList((Collection)arrOrderLineItem);
      }Is there no way except iterating through the array and adding individual Objects to ArrayList?

    By "Object array" do you mean an Array class, or do you mean an Object[]? They are different. The Array class wraps an Object[] and provides useful methods to manipulate it.
    There is no such thing as a Collection object, per say. "Collection" is an interface implemented by many objects such as LinkedList, Vector, ArrayList, HashSet, and TreeSet.
    The Collection interface is designed to be an interface to any object that can keep a mutable list of other Objects, check to see if an Object is in that list, and iterate through all Objects in the list.
    As far as resources go, I suggest the API reference at http://java.sun.com/j2se/1.4.1/docs/api/index.html.

  • Object Array Data Provider Refresh Possible bug

    Hello
    I am having a problem with Object Array Data Provider in terms that the table's data is not changed corectly after a request as expected, but after two requests.
    Steps to reproduce the bug:
    0. Create a new Visual Web project, call it 'test'.
    Set 'Bundled Tomcat ' or 'Sun 9' as deploy target server.
    Edit 'Page1' of the project.
    1. Create an Entity class, simple class that has only getters and setters with a few fields (lets say 'id' and 'name').
    2. In the SessionBean1 that is generated by the framework create an array of Entity class named 'entityArr', and getters and setters for this field.
    3. Add a new Array Object Data Provider on the page and set in its properties as array the array created in the previous step 'entityArr (SessionBean1)'.
    4. Add a new table component, and set as data provider the provider created in step 3.
    In the Table's Layout map the fields from the Entity class, and set whatever compnents you desire for each component's type or leave the default ones (Static Text).
    5. Add a 'property change trigger component' on the page. I called it like this because I tried the following :
    5.1 A text field and a button to submit the text value
    5.2 A Calendar component with autosubmit
    5.3 A DropDown with autosubmit.
    6. On the property change trigger component created at step 5 set a value_changed method that changes the the array that should be displayed by the table.
    For Example, for a DropDown component, you will have a method like this :
    public void dropDown1_processValueChange(ValueChangeEvent event) {
    String idStr = (String) event.getNewValue();
    System.out.println("Entity id :"+idStr);
    if(idStr .equals("item1")) {
    fillSessionBean1(true);
    else {
    fillSessionBean1(false);
    getSessionBean1().setItemName(idStr);
    private void fillSessionBean1(boolean fillValues) {
    Entity[] values ;
    if(fillValues) {
    values = new Entity[4];
    for ( int i=0;i<values.length; i++) {
    Entity entity = new Entity();
    entity.setDescription("Description "+i);
    entity.setName("Name "+i);
    entity.setId(i) ;
    values[i] = entity;
    else {
    //values = new Entity[0];
    values = null;
    getSessionBean1().setEntityArr(values);
    7. When running the program, if the selected is Item1, the table does not show the array set if on this branch.
    I am using :
    Netbeans 5.5 build 20061017100,
    Visual Web Pack 070104_2,
    Ent.Pack 20061212
    jdk 1.6.0
    Operating Systems : Both Linux Suse10 and Windows.
    If anyone has a solution for this please let me know.

    OK
    While no one responded, I had to think for myself.
    There is a bug in the code generated by netbeans or there is nowhere specified that if you attach an array to a data provider you will have to notify by hand the data provider that the array has changed.
    You will have to put this line that is generated in init function in your valuechanged functions :
    objectArrayDataProvider1.setArray((java.lang.Object[])getValue("#{SessionBean1.entityArr}"));
    I think this aproach is a little bit wrong, even it works.
    I believe the data provider should be notified the array has been changed.
    There could be a much more simple aproaches :
    1. In the code generated by netbeans, if you attach an array to a data provider the data provider will be notified after any set(Object[])
    2. The data provider could have a function so you will ne anle to attach to the data provider an Object (the session bean, in my case) and the name of the function that retrieves the array (in my case, 'getEntityArr') .
    The code generated by netbeans could add this function easily.
    Maybe there are any other better aproaches, and I might be wrong.
    It's good that it works.

  • How can I create a variable size array?

    How can I create a variable size array?

    ok then how can i create a new vector object?If you don't know that, you need to go back to your text book and study some more. Or read the tutorial on the basics of Java: http://java.sun.com/docs/books/tutorial/java/index.html
    After reading that you can move on to: http://java.sun.com/docs/books/tutorial/collections/index.html
    Anyway, the answer to your question is, of course:
    Vector v = new Vector();(But you should probably use ArrayList instead of Vector.)

  • Retrieved data from database assignd to object array

    Hi all,
    Im new to java. I creat class it has item_name,item_qty,item_price as properties.then i need to create object array type of that class.now i need to assign values to properties in each element of object array from the database.in my database has ITEM table it has data according to that properties of class.how i do this.please tel me .
    thanks in Advanced,

    Harsha_Lasith wrote:
    yes I knew connect to the database using JDBC.but i have not clear understand about instantiate an object of a class using a constructor.please give me some example for those.
    thanks in advance.If you don't know how to use constructors you really should not be trying to use the JDBC. Learn Java first.

Maybe you are looking for

  • Problem with long text

    Hi folks, iam uploading longtext in transaction KP06 in bdc programing using create_text. now my problem is if i pass selection criteria case 1: Vertion : N0 fiscal year : 2007 planner profile: CCPLAN4 then the budeget plan data uploading successfull

  • Iphone 6 and ipad mini not charging after update to iOS 8.02

    after updating iPhone 6 and iPad mini to iOS 8.02 neither of them will charge on my Bose Soundock Portable using a genuine Apple 30 pin to Lightning adapter however, my 5S running 8.0 still charges

  • Port number of Precalculation Service

    Dear SAP Expert For any security reason, I will implement a firewall program. I have a plan to close all the ports and will make some exception of the application which we use. One of the exeception is Precalculation service. So, Can you tell me what

  • Basic type show in WE05 not same as per defined

    Hi All, I have created a customised message type ZMATMAS1, using customised basic type ZMATMAS1 too. already assigned in WE81 WE82 BD69 & activated in BD50 When idoc generated from BD21, I found that the idoc in WE05 shows the  basic type is MATMAS05

  • Spry table formatti g

    How do you format a spry table field, such as a numeric field to look like currency with 2 decimal places and commas at the thousands?  I can do this in a regular dynamic table field, but can't find how to do it in a spry table. Thanks. Judy