Creating dynamic array

Can anybody tell me how to create a dynamic array in Java??I dont want to fix size of array,it should take any number of values at runtime.Please tell me the syntax of using dynamic arrays.

Hi,
For creating an array of similar data elements, use
ArrayList., but for storing elements which are in the
form of object then use Vector...
Best of Luck..
R SWrong... the main different between ArrayList and Vector is that Vector was sychronized and ArrayList are not.

Similar Messages

  • Reflection question: Creating dynamic array classes

    I'm trying to create a String[].class dynamically by passing into a method the value "String[]" and then returning the Class, but I can't get my head around creating an array version.
    e.g.
    public Class classFromName(String className)
    return Class.forName(className);
    but it fails on arrays passed in. Fine for "String", but not "String[]" or "String[][]".
    Is this possible?
    Thanks
    Mark Fisher ([email protected])

    I couldn't get just "String" to work.
    But remember that you usually write just "String" in source code because there's an implicit import java.lang.* statement at the beginning of your Java source code. That means that "java.lang.String" is the full name of the class. Imports apply onto to source code and are not "remembered" after the compilation process is finished.
    If you want an array of Strings, the JVM name for that class is "[Ljava.lang.String;". I think there's also a way of getting the class object for array types in the reflection classes... I'll let you look for that in the API docs.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Problem in creating dynamic array field.

    Hi there,
    Following are the steps we followed to dynamically build the array field.
    1) Single column array field created with a single widget in the design time.
    2) Few more columns were added using 'Addcolumn' method.
    3) Data in the array object mapped to the array field is populated.
    4) All the dynamic field state was set to FS_UPDATE.
    5) Used Updatefieldfromdata method in all levels ( window, compound field, field widget).
    Problem faced
    1) Data is not visible in the dynamic fields created. But the data is visible in the field created during design time.
    Appreciate, if given any solution for this.
    Regards,
    Anand.

    if you don't see your text, you're not embedding the font.
    when you use actionscript to embed a font, you need to have the font in your library with a linkage id, create a textformat instance and assign its font property and finally assign the textformat to your textfield.  for example
    _root.createTextField("txt",_root.getNextHighestDepth(),50,50,50,50);
    _root.txt.embedFonts=true;
    _root.txt.text="hello";
    _root.txt._rotation=20;
    var tfor:TextFormat=new TextFormat();
    tfor.font="yourfontslinkageid";  // <- linkage id of font in your library
    _root.txt.setTextFormat(tfor);

  • How create dynamic array?

    i have some code....
    public static Object[] parseObjectArray( String type, int size ) {
    if ( !TypeUtil.isSupportedType( type ) ) {
    throw new IllegalArgumentException( "Not supported type:" + type );
    try {
         if ( "String".equalsIgnoreCase( type ) ) {
              return new String[size];
         else if ( "Integer".equalsIgnoreCase( type ) ) {
              return new Integer[size];
         else if ( "Long".equalsIgnoreCase( type ) ) {
              return new Long[size];
         else if ( "Float".equalsIgnoreCase( type ) ) {
              return new Float[size];
         else if ( "Double".equalsIgnoreCase( type ) ) {
              return new Double[size];
         else if ( "Byte".equalsIgnoreCase( type ) ) {
              return new Byte[size];
         else if ( "Short".equalsIgnoreCase( type ) ) {
              return new Short[size];
         else if ("BigDecimal".equalsIgnoreCase(type)) {
              return new java.math.BigDecimal[size];
         else if ( "BigInteger".equalsIgnoreCase( type ) ) {
              return new java.math.BigInteger[size];
         else if ( "Boolean".equalsIgnoreCase( type ) ) {
              return new Boolean[size];
         else if ( "Character".equalsIgnoreCase( type ) ) {
              return new Character[size];
    catch ( Exception ex ) {
         throw new IllegalArgumentException( "Not compatible value tyep" );
    return null;
    The problem is it work only J2SE or over.
    it don't work on CDC beacause java.math.BigDecimal
    That class is not included in CDC
    But, my application is intended to work J2SE and CDC
    So, i think "use the reflection" but there are no solution that I found.
    Class c = Class.forName("[Ljava.math.BigDecimal;");
    Object o = c.newInstance();
    first line(Class.forName...) work well, but next line raise an Exception
    java.lang.InstantiationException: [Ljava.math.BigDecimal;
    also, it can not set size to array that is created
    anyone know solution, please reply or mail to me!! please!

    well I know of a better way to do this in j2se which is using java.util.ArrayList. I dont know if this works in CDC. Hope this helps

  • How to mention numbers in array while creating dynamic sql

    Hi,
    I am creating a dynamic sql and in that I am selecting some rows from the table and storing it into the array.
    I am firing this sql statement within trigger.
    But i got the error:
    ORA-06502: PL/SQL: numeric or value error: character to number conversion error
    I took the same sql statement (the one which was created dynamically) in the procedure and tried to run it but it gave me the same error.
    =========================================================
    Begin
    type NewValueArray is table of varchar2(4000);
    nVal_Array NewValueArray;
    Begin
    Select
    DISCOVERYHOSTNAME,
    DISCOVERYMACPRIMARYPHYSICAL,
    DISCOVERYSERIALNUMBER
    into
    nVal_Array(1),
    nVal_Array(2),
    nVal_Array(3)
    from ALT_42_Consolidated
    where rowid = 'AAEWNEABXAAAAkxAAA';
    EXCEPTION
    WHEN others THEN
    Raise;
    End;
    =========================================================
    I tried using to_number but still the same error.
    Can some body please inform me where I am goofing.
    Thanks!

    I got a different error, but you need to initialise your nval_array and make sure it can hold three values. The following should work:
    declare
      type NewValueArray is table of varchar2(4000);
      nVal_Array NewValueArray := NewValueArray();
    Begin
      nval_array.extend(3);
      Select col1, col2, col3
      into nVal_Array(1), nVal_Array(2), nVal_Array(3)
      from tab1
      where rowid = 'AAAGJZAAGAAAAAWAAV';
    EXCEPTION
      WHEN others THEN
        Raise;
    End;
    /

  • Creating a dynamic Array

    Thanks for reply.
    I want to create a dynamic array and for this I used ArrayList Collection and Vector Class. I am using JDK 1.4.1 . But , I have a problem in that. In ArrayList, I used the following code:
    ArrayList al = new ArrayList();
    while(rs.next())
    al.add(rs.getString("Enter_Year"));
    al.add(rs.getString("UG_Production_Mi_Te"));
    al.add(rs.getString("OC_Production_Mi_Te"));
    al.add(rs.getString("Total_Production_Mi_Te"));
    al.add(rs.getString("OBR_MM3"));
    al.add(rs.getString("OMS_Te"));
    al.add(rs.getString("Coal_Offtake_Mi_Te"));
    al.add(rs.getString("Supply_to_Steel_Plant_Th_Te"));
    al.add(rs.getString("Royalty_SalesTax_MP_Crs"));
    al.add(rs.getString("Royalty_SalesTax_CG_Crs"));
    al.add(rs.getString("Total_ManPower"));
    al.add(rs.getString("Fatality_Rate_per_Mi_Te_Output"));
    al.add(rs.getString("Total_Wellfare_Expenditure_Crs"));
    String rpt[][] = new String[al.size()][];
    rpt = al.toArray(rpt); // ArrayStoreExecption error
    String colheads[] = {"...........My Table's Column names are here....."};
    JTable table = new JTable(rpt,colheads);
    JScrollPane jsp = new JScrollPane(table);
    add(jsp);
    At the statement having comment line I received the error ArrayStoreException. The JTable accepts the 2 D array for storing the info and I think the toArray() method is not working there and can't convert the ArrayList elements into an Array. Similarily, Vector Class is also not converting the elements into an array object and showing the same error only.
    Please help me to convert it into an array object so that I can pass it into the JTable argument.

    That isn't a jdbc problem but rather a collection problem.
    You certainly can't convert a one dimensional collection into a two dimensional array automatically. And that is what you are creating with the while loop.
    Since you know the column names you also know the inner array size so you can start by creating a statically sized string array (not collection) in the loop and add that to the outer collection. That might solve the problem.

  • Creating dynamic sized arrays and filling them automatically on speedy 33

    hi all,
    I am trying to create dynamic sized arrays on Speedy-33. Specifically, depending on the user input, I want to be able to create
    arrays with 128 or 256 elements and fill them automatically. However,
    array constant element is fixed for Speedy 33; thus I have to manually set the
    size of the array with the mouse and enter the values in to the array by
    myself. I want to make this tedious process automatic. Would this be possible? thanks so much for comments!
    ~casiopea

    Casiopea,
    There is a really great article on using arrays with LabVIEW DSC which can be found here:
    How Can I Be Successful With Arrays In the LabVIEW DSP Module?
    One of the biggest things that should be noted about DSP is that there is no dynamic memory allocation.  Your array size must be fixed, and thus, your array needs to be initialized by using a constant. 
    An easy way to initialize an array constant that has many elements that are all the same is to simply create a numeric constant that has the value that you want.  Then, create a new blank array constant and drag the numeric into it.  In the index input for the array constant, type in the index of the last element that you want to be initialized.  Then type in the value in the element that is displayed and all of the elements before it will be initialized to the default value of the numeric constant that you dropped into the array constant.  I hope this helps.  I would really recommend reading through that article, as it has a lot of great information about using arrays with DSC.
    Brian Coalson
    Software Engineer
    National Instruments

  • How do you create an array of clusters dynamically

    I have created a cluster of 3 elements (string, I32, I32) dynamically then I want to create a 1D array of clusters dynamcally as well, but I am having trouble creating the array of clusters .  If anybody has any suggestions please help.  I will really appreciate it, Thank You

    You are not building your array correctly.  What you are doing is taking a single element array of data you just read and replacing it with an empty data set.
    Look at the following ways of doing this.  The one in the middle is only available in later versions of LV, but is supposed to handle memory more effeciently.  But, both the top and middle basically do the same; I preallocate memory for the rows and columns, then replaces the element of the array with the current row and columns data.  The output of the loop with have a 2-D array of all the data.
    The bottom example does create an empty array before the loop runs and uses the indexing feature of the for loop to build the array for you.  All gve you the same result as far as data in your array is concerned.
    Message Edited by Matthew Kelton on 10-05-2007 02:56 PM
    Attachments:
    Cluster Array.png ‏13 KB

  • Creating a dynamic array in Actionscript

    I am wondering how I would create a dynamic array in Acionscript, i.e. one that utilizes fields for mapping data like this:
    public var SMITH:Array = [
               {date:"29-Aug-05", close:45.87, profit:52},
               {date:"23-Aug-05", close:45.74, profit:32},
               {date:"21-Aug-05", close:45.77, profit:22},
               {date:"25-Aug-05", close:46.06, profit:51},
    but where you would just be reading in data without knowing what your data looks like.  In other words, I'd like to take something like a database table with X number of columns and have Actionsctipt map each row to an item in my array.  Something like this:
    for each row in table
    add {col1:value, col2:value, col3:value, ... colX:value} to Array
    So I won't know "date" or "close" or whatever at runtime, I'll just have X number of items for each element in the array. How would this be done?
    The reason I need this mapping feature is because I then want to map the table-like array as the data provider to charts, datagrids, etc.
    Thanks.

    If this post answers your question or helps, please mark it as such.
    You can download the lib for JSON in Flex here:
    http://code.google.com/p/as3corelib/downloads/list
    These pages describe using JSON and Flex, and databases:
    http://www.switchonthecode.com/tutorials/flex-php-tutorial-transmitting-data-using-json
    http://www.switchonthecode.com/tutorials/using-flex-php-and-json-to-modify-a-mysql-databas e
    http://www.switchonthecode.com/tutorials/flex-php-json-mysql-advanced-updating
    http://www.mikechambers.com/blog/2006/03/28/tutorial-using-json-with-flex-2-and-actionscri pt-3/

  • How to create dynamic Invoice report based on Tax calculations

    Hi Ppl,
    I have an invoice report requirement. There are multiple line items in invoice and each line item will have a tax % and discount associated with it. Discount has to be applied at line item level. Tax will be applicable on resultant amount which respect to tax share on total amount. Below is example
    Part# Tax     Qty     UnitPrice Amount     Discount     Net Value
    1     12.5%     40     10          400          100          300
    2     12.5%     50     20          1000          200          800
    3     4%     10     30          300          50          250
                             SubTotal                    1350
                             VAT 12.5% on 1100(300+800)     137.50
                             VAT 4% on 250               10
                             Total Amount               1497.5
    I have created a static rtf which does all calculations correctly. I have hardcoded 12.5 and 4 % tax values for calculations. But issue is that taxes are changeable in future so I want to create dynamic template which takes care for tax calculations. I thought of to create an array to store distinct tax values from XML data and then to perform calculation but don’t know how to do that.
    Can some body help me out as this is very critical and urgent?
    Note: Tax calculation can be done at line item level itself but there are some scenarios where additional discounts are there so tax calculation can not be done at line item level.
    Below is the sample XML data
    <?xml version="1.0" encoding="UTF-8" ?>
    - <ListOfBipActionTest>
    - <Action>
    <AccountId>1</AccountId>
    <PartName>17211KCC900LS</PartName>
    <TAX>12.5</TAX>
    <QTY>40</QTY>
    <UNITPRICE>47.06</UNITPRICE>
    <DIS>15.00</DIS>
    <TaxType>CST</TaxType>
    </Action>
    - <Action>
    <AccountId>2</AccountId>
    <PartName>17213KCC900LS</PartName>
    <TAX>12.5</TAX>
    <QTY>50</QTY>
    <UNITPRICE>19.53</UNITPRICE>
    <DIS>8.00</DIS>
    <TaxType>CST</TaxType>
    </Action>
    - <Action>
    <AccountId>3</AccountId>
    <PartName>28302KAG900S</PartName>
    <TAX>12.5</TAX>
    <QTY>50</QTY>
    <UNITPRICE>59.49</UNITPRICE>
    <DIS>15.00</DIS>
    <TaxType>CST</TaxType>
    </Action>
    - <Action>
    <AccountId>4</AccountId>
    <PartName>2830AKAG900S</PartName>
    <TAX>12.5</TAX>
    <QTY>10</QTY>
    <UNITPRICE>168.7</UNITPRICE>
    <DIS>15.00</DIS>
    <TaxType>CST</TaxType>
    </Action>
    - <Action>
    <AccountId>4</AccountId>
    <PartName>91001GF6000S</PartName>
    <TAX>4.00</TAX>
    <QTY>60</QTY>
    <UNITPRICE>115.34</UNITPRICE>
    <DIS>17.00</DIS>
    <TaxType>CST</TaxType>
    </Action>
    </ListOfBipActionTest>
    Thanks
    Ashish

    Dear Efstratios Kara,
    I installed SAP Integration Kit 3.1. Yes I installed the integration kit after installing CR.
    I have uninstalled the earlier version and i have reinstalled CR with (12.3.0.601) version.
    But still i cant view the SAP connectivity. can u tell me from which version they have included this connectivity option in CR.
    If CR going to support SAP Table connectivity on specific version, what is that version.
    Waiting for your reply.
    Regards,
    Suman

  • Populating a dynamic array with objects and managing it in runtime.

    So I'm another stuck firstyear. I'll try and make my question compact. I'm using Flash CS6 and have drawn an animated character on the stage that consists of separate parts that are animated and its head is a separate class/symbol entirely because it has not only animation, but a state switch timeline as well. This said Head extends the Main that is the character MovieClip.
    I am using a dynamic array to store and .push and .splice objects of another class that would collide with this said Head.
    I also discovered the super() function that is implicitly called as the constructor of the parent in any child class that extends the parent, in this case Head extends Main. The issue is that my collidable object array is populated within the main, within the function that spawns every next collidable object with a TimerEvent. This said function then gets called twice due to the super() call.
    I have tried putting this super() call into an impossible statement in my child class, but it doesn't change a thing, and it was said that this method is unsafe so I don't even know if it should be working.
    However what confuses me the most is when I trace() the .length of my collidable object array at the end of that function. As I said earlier, the original function both spawns an object after a period of Timer(1000) and adds it to the stage as well as adds the object onto the object array, but the super() constructor only duplicates the length call and a creates a copy of the object on the stage, but it does not add the second copy of the object onto the array. The trace() output goes on like so:
    1
    1
    2
    2
    3
    3
    4
    4
    etc.
    I wonder why and I'm really stumped by this.
    Here is the code in question:
    public class Main extends MovieClip {
                        public var nicesnowflake: fallingsnow;
                        var nicesnowflakespawntimer: Timer = new Timer(1000);
                        public var nicesnowflakearray: Array = new Array();
                        public function Main() {
                                  nicesnowflakespawntimer.addEventListener(TimerEvent.TIMER, nicesnowflakespawn);
                                  nicesnowflakespawntimer.start();
                        public function nicesnowflakespawn(event:TimerEvent) : void {
                                  nicesnowflake = new fallingsnow;
                                  nicesnowflake.x = Math.random()* stage.stageWidth;
                                  nicesnowflake.y = - stage.stageHeight + 100;
                                  nicesnowflakearray.push(nicesnowflake);
                                  stage.addChild(nicesnowflake);
                                  trace(nicesnowflakearray.length);
                                  for (var i:Number = 0; i < nicesnowflakearray.length; i++){
                                            nicesnowflakearray[i].addEventListener(Event.ENTER_FRAME, snowhit);
                        public function snowhit(event:Event) : void {
                                  if (nicesnowflakearray[0].y >= 460){
                                            if (nicesnowflakearray[0].y == stage.stageHeight) {
                                            nicesnowflakearray.splice(nicesnowflakearray.indexOf(nicesnowflake), 1);
                                  //if (this.hitTestObject(nicesnowflake)){
                                            //trace("hit");
    I am also fiddling with the collision, but I believe that it would sort itself out when I deal with the array pop and depop properly. However I'm pasting it anyway in case the issue is subtly hidden somewhere I'm not looking for it. And here is the child class:
    public class Head extends Main {
                        public function Head(){
                                  if (false){
                                            super();
                                  this.stop();
    So like what happens at the moment is that the array gets populated by the first object that spawns, but there is two objects on the stage, then when the objects reach stage.460y mark the array splices() the one object away and displays an error:
    "#1010: A term is undefined and has no properties.
              at Main/snowhit()"
    then when the next object spawns, it repeats the process. Why does it trace the array.length as "1, 1, 2, 2, 3, 3, 4, 4, 5, 5, etc" until the despawn point and then goes on to display an error and then starts from 1 again, because if the array length is more than one object at the time when the first object of the array gets spliced away, shouldn't it go on as usual, since there are other objects in the array?
    Thank you very much to whomever will read this through.

    There are multiple problems:
    1. You should add eventlisteners for your objects only once, but you add eventlisteners every time your timer runs to all of your snowflakes, again and again:
                                  for (var i:Number = 0; i < nicesnowflakearray.length; i++){
                                            nicesnowflakearray[i].addEventListener(Event.ENTER_FRAME, snowhit);
    change it to
    nicesnowflake.addEventListener(Event.ENTER_FRAME, snowhit);
    I don`t see why its even necessary to employ this snowflakearray, it would be much straight forward if you simply let the snowflakes take care of themselves.
    2. Then you have to change your enterframe function accordingly
    public function snowhit(event:Event) : void {
                                  if (e.currentTarget.y >= 460){
                                            if (e.currentTarget.y == stage.stageHeight) {
                                            e.currentTarget.removeEventlistener(Event.ENTER_FRAME, snowhit);
                                            removeChild(e.currentTarget);
    3.
                                  //if (this.hitTestObject(nicesnowflake)){
                                            //trace("hit");
    since "this" is a reference to the Main class (root) it surely won`t function as you intend it to.
                                  if (false){
                                            super();
    makes no sense to use a condition that can never be true

  • Creating dynamic textbox in JSP

    I am trying to create dynamic textbox.when i run this below JS ,I am getting two boxes only and then i nothing getting it displayed.The problem comes in the inner for loop.
    function DynamicBox(val)
                        alert("helloooo");
                         var d =document.getElementById("bottom");
                         d.innerHTML = '<table cellpadding="10">';
                        for(i=0;i<val;i++)
                                d.innerHTML += '<tr><td><INPUT type="text" name="week'+i+'" size=8 >  </td><td><INPUT type="text" name="deliverable'+i+'" size=30>  </td>';
                              for(j=1;j<=<%=parameter.length%>;j++)
                                       <% int m=0;%>
                                      d.innerHTML+='<td><INPUT type="text" name="'+<%=parameter[m]%>+i+'" size=10></td>';
                                      <% m++; %>
                                 d.innerHTML +='</tr><br />';
                            d.innerHTML+='</table>';
                    }In the above code,val is the number of rows to be created.Bottom is the id of the <div> tag.parametr is a String array.The values are coming from database.

    move the <% int m=0;%> out of the loop.. You have place it in the loop, causing it to be initialize to be 0 each time the looping occurs.
    Place <% int m=0;%> below the line: d.innerHTML = '<table cellpadding="10">'

  • How to create dynamic variable in Java?

    Hi,
    I want to create dynamic varible , using ArrayList or Vector. The number of array i dont knwo, so how to create dynamic ArrayList or Vector.
    for example:
    ArrayList1,ArrayList2,ArrayList3.....n
    or
    Vector1,Vector2,Vector3 .....n, the n value i will get at run time, so how to create the dynamic ArrayList or Vector or i can use any other Object in java,
    Pls provide your input.
    Sridhar

    1. I have a HashMap with dataok ... fair enough.
    2. depending on its size, i need to create variable
    to store them.uhm ... why? If you have a variable number of elements in the map then you'd need to generate a variable number of variables (a number, that is not know at compile time, as it seems). Now if you could somehow create those variables, how would you access them? You'd have to generate the code handling them as well ...
    Tell us what kind of data you've got and what you want to do with it. There's certainly a better solution to your problem.
    how to generate variables as per content size of the
    HashMapYou don't.

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

  • Creating many arrays with different names

    I'm trying to create many arrays with a different names by calling this method:
    n=name of array
    c= some string
    public Array[] newArray(String n, String c)
    n[n.length]= new String();
    n[n.length]= c;
    As you experts might guess this does not compile. Is it even possible to do this?

    no, you cannot make a dynamic variable like that.
    and no, that is not the way to make arrays.
    and no, there is no such thing as "Array[]" ( unless u have made an "Array" object ).
    code for a new array is as such
    public Object[] newArray(int size){
      return new Object[size];
    }called as such:
    String[] strings = (String[]) newArray(10);
    strings[0] = "hmmm";mmmmm

Maybe you are looking for

  • Mounting any and all Time Machine Backups?

    I have a 2 TB Time Capsule that is serving as my wireless router.  None of my Macs are hardwired to it.  It is backing up 4 Macs.  The newest Mac is a 27 inch iMac that I cloned from the Mac it will replace (24 inch iMac).  I know that in Migration A

  • Migration from Macbook (Core Duo) to New iMac

    Yesterday I bought a new iMac for everyday use while wanting to keep my 2 year old MB for traveling. I used the migration assistant but it also gave me all the settings of the MB including it's name. How do I change this?

  • Looking for a contact number

    does ANYBOBY have a number to get in contact with this dang so called company????

  • Keychain password corrupt

    All of a sudden, I am getting the message that my keychain password is not correct when I attempt to enter it. If I am using Chrome and click cancel, it fills in my saved password anyway. If I open the keychain access program, and attempt to see any

  • PC Suite 7.1.30.9 hangs on instal with Vista Busin...

    Was getting error messages with npcs so installed the latest version (probably the one I already had installed) 'over the top All went fine until reboot after inserting my password when requested on start up in the top rhs was a small dialogue box wi