Dynamically create objects at runtime - Collections?

Dear Experts
During runtime i need to create several objects. Can you help me by pointing out the best practice here? Is it possible to store Man and Dog object in the single collection?
Thank you for the help
The code is as follows
abstract class Mammal {
    String name;
    Mammal(String n)
        name = n;
    void sleep()
        System.out.println( name + "! is asleep! zzzzzzz!");
    abstract void talk();
class Man extends Mammal {
    Man(String n)
        super(n);
    void talk()
        System.out.println("H1 My Name is "+name+" How do you do?");
class Dog extends Mammal {
    Dog(String n)
        super(n);
    void talk()
        System.out.println("Wrf!Wrf!");
public class Main {
    public static void main(String[] args) {
       Dog d1 = new Dog("Dots");
       Man m1 = new Man("Joe");
       Dog d2 = new Dog("Dollar");
       Man m2 = new Man("Mike");
       // ideally i would like to push this into collection of objects
}

standman wrote:
thank you
i tried this. If it is wrong please let me know. If all you need is a List, it may work fine. I didn't try it. Some suggestions:
Declare 'al' as a List:
List al = new ArrayList();Then if you decide you need a LinkedList or other List, you only have to change the right side construction.
Try to use generics (as YoungWinston suggested).
Use an Iterator or an "enhanced 'for' loop" for the iteration, instead of constantly checking "size" and using "get(i)". Since you have a short random-access list (ArrayList), your loop may work okay. But, if you had a long non-random-access list (such as LinkedList), an Iterator or "enhanced 'for' loop" (which uses an Iterator behind-the-scenes) would work faster.
If you do need thread-safety, there are other considerations, too.

Similar Messages

  • Dynamically created object

    Hi
    I did not find any way of accessing a dynamically created
    object by using notation this[id].
    As the code below shows, only hard coded id objects are
    recognised by this[id] notation.
    Any way to do it ?
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    creationComplete="init()">
    <mx:Script>
    <![CDATA[
    import mx.controls.*;
    public var l:Label;
    public function init():void {
    l = new Label();
    l.id = 'label1';
    l.text = 'firstname';
    addChild(l);
    public function fred(event:Event):void {
    mytextarea1.text+=this['mytextarea1'].name + '\n';
    mytextarea1.text+=this['label1'].name + '\n';
    ]]>
    </mx:Script>
    <mx:TextArea id="mytextarea1" width="1300"
    height="200"/>
    <mx:Button click="fred(event)" />
    </mx:Application>

    Thanks guys but I think my example is too simple compared to
    my "real world" current problem ...
    In my project, I dynamically create containers and children.
    I'd like to reach directly a then dynamically created child by its
    id, but notation this[id] is not recognised.
    A better example : form f1 (id='form1) contains 2 labels (ids
    'form1label1' and 'form1label2') ; f1 is included in form f0.
    Calling this['form1label1'] crashed even though it is a
    declared id control ! The same example using <mx> tags would
    not crash...
    And I have gone aroud 10000 articles but never found an
    answer to this.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    creationComplete="init()">
    <mx:Script>
    <![CDATA[
    import mx.controls.*;
    import mx.containers.*;
    public function init():void {
    var f0:VBox = new VBox();
    var f1:VBox = new VBox();
    var l:Label;
    f0.id = 'form0';
    f1.id = 'form1';
    l= new Label();
    l.id = 'form1label1';
    l.text = 'mobile';
    f1.addChild(l);
    l = new Label();
    l.id = 'form1label2';
    l.text = 'work';
    f1.addChild(l);
    f0.addChild(f1);
    addChild(f0);
    public function fred(event:Event):void {
    mytextarea1.text+=Label( this['form1label1'] ).text + '\n';
    ]]>
    </mx:Script>
    <mx:TextArea id="mytextarea1" width="1300"
    height="200"/>
    <mx:Button click="fred(event)" />
    </mx:Application>

  • Nesting dynamically created movieclip at runtime?

    Is it possible to nest a movieclip into another dynamically
    created movieclip at runtime? The commented line of code works, but
    I am trying to nest a movieclip after it is created into
    another.

    you can nest movieclips by using your commented code.
    however, you cannot change a movieclip's parentage after it's
    created.
    you can "fake" a parentage change by creating a movieclip
    with the parentage you want, copying its assets to the newly
    created movieclip with the desired parentage and finally removing
    the original movieclip.

  • ABAP OBJECTS: Dynamic Create object

    Hi folks!
    I have a problem... I need to create a dynamic type object with:
    <b>DATA: my_instance TYPE REF TO class1.
    CREATE OBJECT my_instance TYPE (class2).</b>
    <i>* where class1 is a superclass of class2.</i>
    When I do:
    <b>my_instance ?= m_parent.</b>
    <i>* where m_parent is an instance of class1</i>
    My problem is when I want to access to an attribute of the class2, the compiler says that it cannot find the attribute <i>(this is OK, because the attribute is only in the class2).</i>
    My question:
    Is there anyway to access to an atribute of second class when is not in the first class? (i don't want to create the attribute as an attribute of the first class).
    Thanx!!!!

    Hi David,
    When you do the debugging, you are dealing with run-time - i.e., the program is now running and you are just interrupting it at each statement to examine the program state. You will reach the point where the object is already created. That is why you can see all those attributes. But when you comiple, the program is not yet <i>running</i>, so the attributes will be unknown because of the dynamic type specification.
    I think you will have to redesign the program logic. As i had already said in my earlier post, it is not proper to have the attributes specified statically while the class itself is specified dynamically.
    Your situation is somewhat similar to -
    DATA ITAB TYPE TABLE OF SPFLI.
    PERFORM TEST TABLES ITAB.
    FORM TEST TABLES ITAB.
      LOOP AT ITAB.
        WRITE: / ITAB-CARRID.
      ENDLOOP.
    ENDFORM.
    Hope the point is clear.
    Regards,
    Anand Mandalika.

  • Create Object when Runtime ?

    Hi, everyone. Is there anybody could give advice about creating object on Forms Runtime? (I mean, I could create eg:Button when in Form runtime). Any help would be appreciated.

    Any help here...
    http://support.microsoft.com/kb/288117
    http://www.macworld.com/article/1154785/welcomebackvisualbasic.html

  • This[id] doesn't see dynamically created objects????

    Hey all!
    If i have
    <mx:Canvas id="TopCanvas" initialize="Init()">
    <mx:Canvas id="VisibleCanvas" >
    </mx:Canvas>
    </mx:Canvas>
    <fx:Script>
    function Init(){
    var NewO = new Canvas();
    NewO.id="InvisibleCanvas";
    TopCanvas.addChild(NewO);
    if (this["VisibleCanvas"]){
    //We can see non-dynamically created canvas
    if (this["InvisibleCanvas"]){
    //ERROR we cannot see the new one!
    Help please! How to access dynamically created Canvases via their id? I know i can save linkage to them in array, but i need to do it through id.
    Cheers!

    If you set the id property on a dynamically created instance, you can check
    the id of an instance later if it happens to be a target of an event, for
    example.  But it will not be assigned to a variable in the document.
    By default, MXML generates a non-dynamic class so you can't add properties
    to it at runtime.  You can set the name property and search the immediate
    parent by calling getChildByName, but if the parent is not the document, you
    still can't search the document.

  • Access dynamically created objects

    Hello!
    I create some images dynamically by running a for from 1 to a
    variable preset. The pictures have the IDs image1, image2 ...
    ("image"+i). I then add other properties.
    Problem is for each I need an onMouseOverHandler thant will
    swap the image with another.
    I can get the target image with event.currentTarget.id. But I
    cannot set it's properties with this["image"+i].source (I need to
    change the ones up to that as well) and I cannot access it with
    this.getChildByName("image"+i).source either.
    What am I doing wrong please?

    "M*A*S*H 4077" <[email protected]> wrote in
    message
    news:go74q6$fbb$[email protected]..
    > Hello!
    >
    > I create some images dynamically by running a for from 1
    to a variable
    > preset.
    > The pictures have the IDs image1, image2 ...
    ("image"+i). I then add other
    > properties.
    >
    > Problem is for each I need an onMouseOverHandler thant
    will swap the image
    > with another.
    > I can get the target image with event.currentTarget.id.
    But I cannot set
    > it's
    > properties with this["image"+i].source (I need to change
    the ones up to
    > that as
    > well) and I cannot access it with
    this.getChildByName("image"+i).source
    > either.
    >
    > What am I doing wrong please?
    ID is about as useful as your appendix when you create
    objects dynamically.
    The event.target property will contain a reference to your
    image.

  • Create object in runtime phase

    Hi all,
    i would create a data grid and pass it an array...
    for example th array looks like this:
    <mx:Array id="planets">
    <mx:Object planet="Mercury" kind="Terrestrial"
    year_duration="0.24" moons="0" cost="1250" />
    <mx:Object planet="Venus" kind="Terrestrial"
    year_duration="0.62" moons="0" cost="2400" />
    <mx:Object planet="Jupiter" kind="Gas giant"
    year_duration="11.86" moons="63" cost="500" />
    <mx:Object planet="Eris" kind="Ice dwarf"
    year_duration="557" moons="1" cost="3000" />
    </mx:Array>
    and datagrid takes dataprovider property equal to "planets".
    ok it'all ok but how can i create an object with those
    properties (planet, kind,...) and values dinamically?
    for example i would create a method that returns a value and
    inserts it in a properties in the object array
    <mx:Object planet = method1() kind = method2() />
    maybe i have to create MyClass that extends Objects...infact
    i see that the dataprovider propertiy is an OBject class...i dont't
    know...
    i appreciate any help..thanks a lot

    Thanks for the reply...
    an other question
    i'have an xml file like this:
    > <root>
    > <week id="1">
    > <production day="monday">
    > <book>23</book>
    > <cds>49</cds>
    > </production>
    > <production day="tuesday">
    > <book>56</book>
    > <cds>68</cds>
    > </production>
    > ...other weeks production...
    > </week>
    > </root>
    i would create objects for every products: book and cds
    for example for book
    <mx:Object monday="23" tuesday="56" />
    and for cds
    <mx:Object monday="56" tuesday="68" />
    can you suggest a procedure to rich this result?
    thanks in advance
    Regards
    Bilbo

  • HOW TO remove nodes add nodes dynamically create objects branchgroup

    After much trial and error, frustration and reading this forum I have come across a good way to dynamically add/remove objects. This is working in my model with 1.3 and jdk 1.4.1_02 Sorry if its sloppy.
    Here goes:
    Adding objects (cap bits may not be optimised):
    (A)
    BranchGroup newDynObj = null;
    switch (workerType)
    case 1: //create a rawEntry BranchGroup
    newDynObj = new RawEntry();
    break;
    case 2: //create a Finshed Node
    newDynObj = new FinishedNode();
    break;
    default:
    newDynObj.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
    newDynObj.setCapability(BranchGroup.ALLOW_DETACH);
    newDynObj.setCapability(Group.ALLOW_CHILDREN_READ);
    newDynObj.setCapability(Group.ALLOW_CHILDREN_WRITE);
    Transform3D t = new Transform3D();
    t.set(scale, new Vector3d(xpos, ypos, zpos));
    TransformGroup objTrans2 = new TransformGroup(t);
    objTrans2.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
    objTrans2.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
    objTrans2.setCapability(TransformGroup.ALLOW_CHILDREN_READ);
    objTrans2.setCapability(TransformGroup.ALLOW_CHILDREN_WRITE);
    objTrans2.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
    Sphere obj = new Sphere(1.0f, Sphere.GENERATE_NORMALS | Sphere.GENERATE_TEXTURE_COORDS,
    5, app);
    //add to scene graph
    objTrans2.addChild(obj);
    newDynObj.addChild(objTrans2);
    newDynObj.compile();
    return newDynObj;
    call this ftn with:
    Space3DPanel.objTrans.addChild(createObject(createAppearance(workerType), 0.04, x, y, z, 2)); where objTrans is your tansformGroup
    Removing branchgroup:
    Its easy to add. But the trick is to delete/remove these !?! Detach doesnt seem to do anything. The method/pattern that works for me is to..
    1. make a new class subclassing BranchGroup like this:
    public class FinishedEntry extends BranchGroup
    { private String type;
    public FinishedEntry(){  }
    public FinishedEntry(String type)
    { this.type = type; }
    and
    public class RawEntry extends BranchGroup
    private String type;
    public RawEntry(){  }
    public RawEntry(String type)
    { this.type = type;}
    2. To when adding the BG to the TG of the parent (objTrans)
    add a BG of the type you subclassed.
    see (A) above.
    3. Now scan through the children of the TG that you have been adding these children to. Like this:
    static synchronized public void removeNodeFromModel(int workerType)
    try {
    switch (workerType)
    case 1: //raw Entry
    for (int i = 0; i < Space3DPanel.objTrans.numChildren(); i++)
    if (Space3DPanel.objTrans.getChild(i) instanceof RawEntry)
    Space3DPanel.objTrans.removeChild(i);
    break;
    break;
    case 2: //result Entry
    for (int i = 0; i < Space3DPanel.objTrans.numChildren(); i++)
    if (Space3DPanel.objTrans.getChild(i) instanceof FinishedNode)
    Space3DPanel.objTrans.removeChild(i);
    break;
    } //end for
    break;
    default:
    } catch (Exception e) { e.printStackTrace(); }
    The main idea is to use instanceof !! then use removeChild (see above).. Also, you can compile your BGs using this method.
    Thanks for the great forum!
    Jacob Pyrett
    [email protected]

    First, to add child nodes to a branch group, you must follow two rules:
    (1) The child you are adding to the branch group is also a BranchGroup
    (2) The BranchGroup.ALLOW_CHILDREN_EXTEND capability is set
    From here, you are able to add children on the fly.
    To remove a child from the branch group was harder to figure out, but I eventually got it to work. To accomplish this you must do the following:
    (1) have the capability BranchGroup.ALLOW_DETACH) set on the child BranchGroup you wish to remove.
    (2) call the child's detach() method rather than calling the parent's removeChild()
    Hope this helps.

  • Accessing dynamically created objects

    If objects are created dynamically in AS3, using code like
    this:
    for (var num:Number = 0; num<10; num++){
    var txtFld:TextField = new TextField();
    txtFld.text = 'This is the original text';
    this.addChild(txtFld);
    then later, i want to changet the text of one of the
    TextFields, how can I do that? The only instance listed in the
    variables is a single instance of "txtFld" and it is the last one
    that is created. How can I access the others?
    Thanks

    Two ways pop to my mind.
    Give them a name property when you create them and then use
    getChildByName().
    Push each instance into an array/vector as you create it and
    then iterate over the values in the array.
    A combination of both?

  • Preloading dynamically created objects

    Hi,
    I have some Object I would like to create on runtime, but it initialization takes some time. So normally I would code something like
    Class SimpleFoo
    private BigObject bO = new bO("parameters here");
    BigObject getBigObject()
    return bO;
    }but now I have a lot (say around 30 in the total class, which is more complicated) of them, so it would be something like
    Class MessyFoo
    private BigObject bOprime = new bO("prime parameters here");
    private BigObject bOeven = new bO("even parameters here");
    BigObject getBigObject(int i)
    if (isPrime(i))
    return bOprime;
    else if (isEven(i))
      return bOeven;
    }which gets really messy. I'd rather code
    Class CleanLookingFoo
    BigObject getBigObject(int i)
      if (isPrime(i))
       return new bO("prime parameters here");
      else if (isEven(i))
        return new bO("even parameters here");
    }but then I miss the caching and initialization advantages. What is the best way to build this? So far my best option is to pre-process the CleanLookingFoo and make a MessyFoo out of it, and then pass it through to the Java compiler, which probably isn't the best solution.

    The usual pattern is to use a synchronization mechanism and a lazy initialiser. The simplest mechanism is to use a holder class with a static field, since it won't get initialised until it's first used:
    public class LazyBigObjects {
         static class BigObject {
              BigObject (String params) {
                   System.out.println(params);
         static class PrimeBigObjectHolder {
              static final BigObject INSTANCE = new BigObject("prime parameters here");
         static class EvenBigObjectHolder {
              static final BigObject INSTANCE = new BigObject("even parameters here");
         public static BigObject getBigObject(int i) {
              System.out.println("getBigObject called with " + i);
              switch (i) {
                   case 0: {
                        return PrimeBigObjectHolder.INSTANCE;
                   case 1: {
                        return EvenBigObjectHolder.INSTANCE;
                   default:
                        throw new IllegalArgumentException(i + " out of range.");
         public static void main (String...args) {
                 getBigObject(0);
              getBigObject(1);
    }Output:
    getBigObject called with 0
    prime parameters here
    getBigObject called with 1
    even parameters here
    The JVM handles synchronisation issues of class initialisation, so you don't need to do anything about that.

  • A dynamic View object at runtime

    Say there is an inputtext component and one LOV. User will enter a number, say 7, and then press a Submit button. And then in the LOV, user will be able to see the numbers from 1 to 7.
    Is it possible to achieve the same?

    Hi,
    am not sure what exactly you are trying to achieve here,
    but from your description, it looks like a query dependency to me..
    So in your VO that will be used as the List of Values for the attribute you want, create a View Criteria that meets the requirement you want (seems like 'Less than or Equal To' is what you need).
    So eventually, you will end up with a ViewCriteria and one bindVarialble in that LOV View Object.
    Since you havent described your BC model, I can only assume that you have one main VO and both UI component are binded to attributes of that VO.
    Now go back to your main VO and update the LOV View AcCessor to use the ViewCriteria specifying the proper value on the Bind Variable.
    Hope this helps,
    Regards,
    Dimitrios.

  • Getting the coordinates of dynamically created objects

    i have created 3 movie clips via actionscript and given them
    instance names of cS_1, cS_2, and cS_3. however, i can't manage to
    trace their x coordinates. i know i gotta do something with
    getChildByName but i'm really stuck and can't figure it out. Could
    someone please explain to me what i have to do like explaining to
    an 8 year old. Thank you!
    Here's the code:

    To use the getChildByName method you want to cast a MovieClip
    variable to capture a reference to it, as in:
    var cs1:MovieClip = this.getChildByName(cs_1);
    trace(cs1.x);

  • Dynamically create object

    i want to write a program that need to connect database.
    The table should be like this:
    uid, type
    1, input
    2, password
    3, report
    And i already have following classes:
    public String input() {...};
    public String password() {...};
    public String report() {...};
    then the java program fetch the row:
    while (next_record)
    the_type = column(type);
    (the_type) new_object = new (the_type)(); //this line is my problem!!!
    Do any one can tell me how to write the above line correctly?

    Thank you!
    i have used forName and newInstance to solve my problem.

  • Dynamic creating SAPBobsCOM objects using reflection

    Hi All,
    I'm writing a tool (C#) for SBO for exporting object (oItems, oBanks etc.) to XML files. And I have a problem how to dynamically create object by it's string description. I'm trying to create it using System.Reflection, but cant't find right way to create it.
    It must be like that, but it doesn't work:
               Type  sboObject = System.Type.GetType("SAPbobsCOM.Items, Interop.SAPbobsCOM", true, true);
               object ibaseObject = Activator.CreateInstance(sboObject);
    Any ideas?)

    Hi
    I've writen this code for instantiating DI API objects using .NET reflection
            private object getObjectBo(int tipo) //tipo: integer representing the object type
                object o = null;
                try
                    Type tipoComp = kernel.Company.GetType(); //Type SAPbobsCOM.Company
                    MethodInfo info = tipoComp.GetMethod("GetBusinessObject");
                    object[] parametros = new object[1]; //Parameters of GetBusinessObject
                    object tipoObj = Enum.ToObject(typeof(SAPbobsCOM.BoObjectTypes), tipo);
                    parametros[0] = tipoObj;
                    o = info.Invoke(kernel.Company, parametros);  //Calling GetBusinessObject           
                catch (Exception ex)
                    kernel.Application.MessageBox(ex.Message, 0, "", "", "");
                return o;
    The object returned is COM object (not managed code) then we can't use .NET reflection directly for exploring its methods and attributes .. I think we should use C++ and IDispatch interface, but i don't know how do this yet.
    Hope it helps.
    Regards

Maybe you are looking for

  • How to print to two printers via network?

    Hi, I just moved into a new house with ethernet cabling throughout. I'd love to print to my two printers (HP LaserJet 1012 and a Canon iP3600) via the network without using a computer. However, I can't figure out how to do it. So far, I've tried: Att

  • How to enable my disabled I pad

    How to enable my disabled iPad

  • Transaction timeout error in 14.0

    Hi, I am working on MII 14.0 SP05. One of my transactions deals with a huge volume of data due to which I get a time out error while executing the transaction in workbench and a NULL alert when I run it from my UI page. I checked running the SQL pack

  • CS4 with two monitors

    I am using 2 monitors with CS4. One monitor is a "tools" monitor, and the other is a color calibrated monitor for retouching my images full screen, with no palettes interfering. When I open an image, it always opens behind my tool palettes on the too

  • Forms R12: install j2se plugin in Linux

    when opening forms in R12 it shows the error like below : In order to access this application, you must install the J2SE Plugin version 1.6.0_07 on your client and NPX_PLUGIN_PATH environment variable is set before starting Netscape. To install this