Array of Object Refs

I am doing exercises in a book (a couple books) to learn Java. I am a procedural pgmr and want to learn Java.
Question 3 in Chapter 4 says:
Create an array of object references of the class you created in Exercise 2, but don't actually create objects to assign into the array. When you run the program, notice whether the initialization messages from the constructor calls are printed.
In exercise 2, I created an created an overloaded constructor. There are two constructors one that takes an argument and one that doesn't. I think I understand that I am being asked to look to see the values of the variables before the object is actually created but after initialization.
My question is that I am not sure I understand what is being asked in question 3. I have to create an array of object references. I understand object references to be the varable names that hole the contents of the object. I don't understand what I am supposed to put into each (the two) elements of the array.
Here is program written for exercise 2:
//: c04:J402.java
/* This has overloaded constructors. However, the argument must be given. Without it, there is an exception at runtime. */
class Bird {
Bird() {
System.out.println("The object is an egg");
Bird(String age) {
System.out.println("The object is " + age + " months old");
public class J402 {
public static void main(String[] args) {
String age = args[0];
new Bird(age);
} ///:~
Thank you so much for any help.

My question is that I am not sure I understand what is
being asked in question 3. I have to create an array
of object references. I understand object references
to be the varable names that hole the contents of the
object. I don't understand what I am supposed to put
into each (the two) elements of the array.
You need to make three different concepts clear to yourself: objects, object references, and reference variables.
Objects are objects are objects. They are self contained entities that live somewhere in the memory. But, as you can't manipulate the memory directly (there are many good reasons for that), you can't manipulate objects directly.
To get to objects you need references (or pointers). A reference is like a memory address. It normally points to the memory location of an object, but if the reference can also be a special 'null' reference that doesn't point to any object (or to every possible object, depending on how you want to look at it). The JVM takes care of talking to the underlaying object through the reference.
An object can have many references pointing to it but a reference can point to only one object (or no / any object in the case of a null reference).
Reference variables, then, are the ones you have in source code. Here's an example of a reference variable:Bird tweety;
tweety = new Bird("I thought I saw a pussy cat!");(given a hypotetical class that can take a String object as an argument to the constructor)
"tweety" is a reference variable. A reference variable is a variable that can hold a reference -- surprise! :). If not set to any particular reference, it's value may be null. If you now do something likeBird bird2 = tweety;
tweety = new Bird();you first define a new ref. variable "bird2" and set its value to tweety's ref. Then you reset the var. tweety to point to a new Bird object. What happens to bird2? Nothing!! ... but if instead of "tweety = new Bird();" you had written "tweety.setChirp("TWEET!!!");" and then called bird2.chirp(), it would have chirped with "TWEET!!!" because the references of bird2 and tweety point to the same object.
But, you can have references outside reference variables. In reference arrays (or "object arrays", the terminology can be confusing), for instance. Then, the codeBird[] flock = new Bird[2];0) Creates, allocates and initializes a new reference array object.
1) Creates a new reference variable called "flock" and assigns it to a reference that points to the object that was created in 0).
2) Creates 2 more references to Bird objects, initially set to null. No further objects are created. These references can be used like reference variables through flock[0] and flock[1].
(not necessarily in this order)
Now this should answer the excersise 3. The references of flock[0] and flock[1] are left as null and they don't point to any objects - They will only if you do something like "flock[0] = new Bird("chirp!");" or "flock[1] = tweety;"

Similar Messages

  • Displaying the contents of an array of objects

    Hello All,
    My Java teacher gave us a challenge and I'm stumped. The teacher wants us to display the contents of the array in the main menthod. The original code is as follows:
    public class TestObjects
         public static void main ( String args[] )
              Thing[] thingArray = { new Thing(4), new Thing(7) };
    }I understand that the elements of the array are objects, and each one has a value assigned to it. The following code was my first attempt at a solution:
    public class TestObjects
         public static void main ( String args[] )
              Thing[] thingArray = { new Thing(4), new Thing(7) };
                                    for ( int i = 0; i < thingArray.length; i++)
                                       System.out.println( thingArray );                         
    }To which I'm given what amounts to garbage output. I learned from reading about that output that its basically displaying the memory location of the array, and the the contents of the array. There was mention of overriding or bypassing a method in System.out.println, but I don't believe that we're that far advanced yet. Any thoughts? I know I have to get at the data fields in the objects of the array, but i'm not having an easy time figuring it out. Thanks very much in advance!

    robrom78 wrote:
    public class TestObjects
         public static void main ( String args[] )
              Thing[] thingArray = { new Thing(4), new Thing(7) };
    for ( int i = 0; i < thingArray.length; i++)
    System.out.println( thingArray );                         
    Note that you're trying to print the entire array at every loop iteration. That's probably not what you meant to do.
    You probably meant to do something more like
                                 System.out.println( thingArray[i] );Also, note that the java.util.Arrays class has a toString method that might be useful.
    To which I'm given what amounts to garbage output. It's not garbage. It's the default output to toString() for arrays, which is in fact the toString() defined for java.lang.Object (and inherited by arrays).
    I learned from reading about that output that its basically displaying the memory location of the array, and the the contents of the array.It displays a default result that is vaguely related to the memory, but probably shouldn't be thought of us such. Think of it as identifying the type of object, and a value that differentiates it from other objects of the same type.
    By the way I assume you mean "+not+ the contents of the array" above. If so, that is correct.
    There was mention of overriding or bypassing a method in System.out.println, but I don't believe that we're that far advanced yet. Any thoughts? No, you don't override a method in println; actually methods don't contain other methods directly. You probably do need to override toString in Thing.
    I know I have to get at the data fields in the objects of the array, but i'm not having an easy time figuring it out. You can get to the individual objects in the array just by dereferencing it, as I showed you above.
    But I suspect that won't be sufficient. Most likely, Thing doesn't have a toString method defined. This means that you'll end up with very similar output, but it will say "Thing" instead of "[Thing" and the numbers to the right of the "@" will be different.
    You'll need to override the toString() method in Thing to get the output you want.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to pass a array of object to oracle procedure using callable

    Hi,
    I am calling a oracle stored procedure using callable statement which has IN and OUT parameter of same type.
    IN and OUT are array of objects. (ie) IN parameter as Array of Objects and OUT parameter as Array of Objects
    here are the steps i have done as advised from oracle forum. correct me if i am in wrong direction
    ORACLE types and Stored Procedure
    CREATE OR REPLACE
    TYPE APPS.DEPARTMENT_TYPE AS OBJECT (
    DNO NUMBER (10),
    NAME VARCHAR2 (50),
    LOCATION VARCHAR2 (50)
    CREATE OR REPLACE
    TYPE APPS.DEPT_ARRAY AS TABLE OF department_type;
    CREATE OR REPLACE package body APPS.insert_object
    IS
    PROCEDURE insert_object_prc (d IN dept_array, d2 OUT dept_array)
    IS
    BEGIN
    d2 := dept_array ();
    FOR j IN 1 .. d.COUNT
    LOOP
    d2.EXTEND;
    d2 (j) := department_type (d (j).dno, d (j).name, d(j).location);
    END LOOP;
    END insert_object_prc;
    END insert_object;
    JAVA CODE
    Value Object
    package com.custom.vo;
    public class Dep {
    public int empNo;
    public String depName;
    public String location;
    public int getEmpNo() {
    return empNo;
    public void setEmpNo(int empNo) {
    this.empNo = empNo;
    public String getDepName() {
    return depName;
    public void setDepName(String depName) {
    this.depName = depName;
    public String getLocation() {
    return location;
    public void setLocation(String location) {
    this.location = location;
    to call stored procedure
    package com.custom.callable;
    import com.custom.vo.Dep;
    import oracle.jdbc.OracleCallableStatement;
    import oracle.jdbc.OracleConnection;
    import oracle.jdbc.OracleTypes;
    import oracle.jdbc.pool.OracleDataSource;
    import oracle.sql.ARRAY;
    import oracle.sql.ArrayDescriptor;
    import oracle.sql.Datum;
    import oracle.sql.STRUCT;
    import oracle.sql.StructDescriptor;
    public class CallableArrayTryOut {
    private static OracleDataSource odcDataSource = null;
    public static void main(String[] args) {
    OracleCallableStatement callStatement = null;
    OracleConnection connection = null;
    try {
    odcDataSource = new OracleDataSource();
    odcDataSource
    .setURL("......");
    odcDataSource.setUser("....");
    odcDataSource.setPassword("....");
    connection = (OracleConnection) odcDataSource.getConnection();
    } catch (Exception e) {
    System.out.println("DB connection Exception");
    e.printStackTrace();
    Dep[] dep = new Dep[2];
    dep[0] = new Dep();
    dep[0].setEmpNo(100);
    dep[0].setDepName("aaa");
    dep[0].setLocation("xxx");
    dep[1] = new Dep();
    dep[1].setEmpNo(200);
    dep[1].setDepName("bbb");
    dep[1].setLocation("yyy");
    try {
    StructDescriptor structDescriptor = new StructDescriptor(
    "APPS.DEPARTMENT_TYPE", connection);
    STRUCT priceStruct = new STRUCT(structDescriptor, connection, dep);
    STRUCT[] priceArray = { priceStruct };
    ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(
    "APPS.DEPT_ARRAY", connection);
    ARRAY array = new ARRAY(arrayDescriptor, connection, priceArray);
    callStatement = (OracleCallableStatement) connection
    .prepareCall("{call insert_object.insert_object_prc(?,?)}");
    ((OracleCallableStatement) callStatement).setArray(1, array);
    callStatement.registerOutParameter(2, OracleTypes.ARRAY,
    "APPS.DEPT_ARRAY");
    callStatement.execute();
    ARRAY outArray = callStatement.getARRAY(2);
    Datum[] datum = outArray.getOracleArray();
    for (int i = 0; i < datum.length; i++) {
    oracle.sql.STRUCT os = (oracle.sql.STRUCT) datum[0];
    Object[] a = os.getAttributes();
    for (int j = 0; j < a.length; j++) {
    System.out.print("Java Data Type :"
    + a[j].getClass().getName() + "Value :" + a[j]
    + "\n");
    connection.commit();
    callStatement.close();
    } catch (Exception e) {
    System.out.println("Mapping Error");
    e.printStackTrace();
    THE ERROR
    Mapping Errorjava.sql.SQLException: Inconsistent java and sql object types
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
    at oracle.jdbc.dbaccess.DBError.check_error(DBError.java:1130)
    at oracle.sql.StructDescriptor.toOracleArray(StructDescriptor.java:823)
    at oracle.sql.StructDescriptor.toArray(StructDescriptor.java:1735)
    at oracle.sql.STRUCT.<init>(STRUCT.java:136)
    at com.custom.callable.CallableArrayTryOut.main(CallableArrayTryOut.java:48)

    You posted this question in the wrong forum section. There is one dedicated to Java that was more appropriate.
    Anyway here is a link that describes what you should do.
    http://download.oracle.com/docs/cd/B19306_01/java.102/b14355/oraarr.htm#i1049179
    Bye Alessandro

  • Property List error: Unexpected character b at line 1 / JSON error: JSON text did not start with array or object and option to allow fragments not set.

    Hi,
    I have a MBP 13' Late 2011 and Yosemite 10.10.2 (14C1514).
    Until yesterday, I was using Garmin ConnectIQ SDK and all was working fine.
    Yesterday, I've updated my system with latest security updates and Xcode updates too (Version 6.2 (6C131e)).
    Since, I can't launch the ConnectIQ simulator app, I have this message in console :
    8/04/2015 15:19:04,103 mds[38]: There was an error parsing the Info.plist for the bundle at URL Info.plist -- file:///Volumes/Leto/connectiq-sdk-mac-1.1.0_2/ios/ConnectIQ.bundle/
    The data couldn’t be read because it isn’t in the correct format.
    <CFBasicHash 0x7fa64f44e9a0 [0x7fff7dfc7cf0]>{type = immutable dict, count = 2,
    entries =>
      0 : <CFString 0x7fff7df92580 [0x7fff7dfc7cf0]>{contents = "NSDebugDescription"} = <CFString 0x7fa64f44f0a0 [0x7fff7dfc7cf0]>{contents = "Unexpected character b at line 1"}
      1 : <CFString 0x7fff7df9f5e0 [0x7fff7dfc7cf0]>{contents = "kCFPropertyListOldStyleParsingError"} = Error Domain=NSCocoaErrorDomain Code=3840 "The data couldn’t be read because it isn’t in the correct format." (Conversion of string failed.) UserInfo=0x7fa64f44eda0 {NSDebugDescription=Conversion of string failed.}
    I have looked at this file and it looks like a binary plist
    bplist00ß^P^V^A^B^C^D^E^F^G^H
    ^K^L^M^N^O^P^Q^R^S^T^U^V^W^X^Y^Z^[^\^]^^^_ !"$%&'()'+,^[\CFBundleNameWDTXcodeYDTSDKName_^P^XNSHumanReadableCopyrightZDTSDKBuild_^P^YCFBundleDevelopmentRegion_^P^OCFBundleVersi    on_^P^SBuildMachineOSBuild^DTPlatformName_^P^SCFBundlePackageType_^P^ZCFBundleShortVersionString_^P^ZCFBundleSupportedPlatforms_^P^]CFBundleInfoDictionaryVersion_^P^RCFBundleE    xecutableZDTCompiler_^P^PMinimumOSVersion_^P^RCFBundleIdentifier^UIDeviceFamily_^P^QDTPlatformVersion\DTXcodeBuild_^P^QCFBundleSignature_^P^ODTPlatformBuildYConnectIQT0611[iph    oneos8.1o^P-^@C^@o^@p^@y^@r^@i^@g^@h^@t^@ ^@©^@ ^@2^@0^@1^@5^@ ^@G^@a^@r^@m^@i^@n^@.^@ ^@A^@l^@l^@ ^@r^@i^@g^@h^@t^@s^@ ^@r^@e^@s^@e^@r^@v^@e^@d^@.V12B411RenQ1V14C109Xiphoneos    TBNDLS1.0¡#XiPhoneOSS6.0YConnectIQ_^P"com.apple.compilers.llvm.clang.1_0S8.1_^P^Tcom.garmin.ConnectIQ¡*^P^AW6A2008aT????^@^H^@7^@D^@L^@V^@q^@|^@<98>^@ª^@À^@Ï^@å^A^B^A^_^A?^AT^    A_^Ar^A<87>^A<96>^Aª^A·^AË^AÝ^Aç^Aì^Aø^BU^B\^B_^Ba^Bh^Bq^Bv^Bz^B|^B<85>^B<89>^B<93>^B¸^B¼^BÓ^BÕ^B×^Bß^@^@^@^@^@^@^B^A^@^@^@^@^@^@^@-^@^@^@^@^@^@^@^@^@^@^@^@^@^@^Bä
    I guess it is a normal format but my system seems to be unable to read binary plist ?
    I tried some stuff with plutil
    plutil -lint Info.plist
    Info.plist: Unexpected character b at line 1
    Same for convert
    plutil -convert xml1 Info.plist
    Info.plist: Property List error: Unexpected character b at line 1 / JSON error: JSON text did not start with array or object and option to allow fragments not set.
    I also try to download a fresh version of the connectIQ SDK and no changes.
    Any idea ?
    Thanks

    Step by step, how did you arrive at seeing this agreement?

  • WRT160N - LELA FAILED - ERROR - MSG_100_000_003 & Object ref not set to an instance of an object

    First of all I would like to say I'm very disappointed with Cisco/Linksys support. I made 6 phone calls and spent about 3 hours on hold and being connected to someone else over the course of about two weeks. The Tech supportin this particular case was the worst I have ever experienced. Regarding the problem - make sure that you do not have any items in the start up such as Linksys EasyLink Advisor and in particular nmctxth unchecked. Also, check that your Anti-Virus does not have the app blocked. I was instructed to uninstall and reinstall about six different times - which I did. This never solved anything. Then I notice a program named "Pure Networks", this appears to be app associated with LELA. The best I could tell this does not get uninstalled and reinstalled like the rest of the program. So I chased the app down to Documents and Settings\All Users\Application Data\Pure Networks\Setup\PlatformSetupInstaller_0.msi . Executed this program which initiated an install program for the same and selected the REPAIR option from the three options (Repair\Modify\Uninstall). After about two or three minutes the program indicated the Repair had completed and the PC needed to be rebooted. Which I did and now the program (LELA) works with no issues. I think when you uninstall and reinstall the LELA program this never gets executed. So when you manually run the program it actually gets executed. I performed this Repair when the file: PlatformSetupInstaller_0.msi was selected and actually executed. The following error messages were indicated before the issue was resolved:
    Error
    MSG_100_000_003
    Cannot find Platform service, make sure that the service is correctly installed on your machine.
    Error
    Object ref not set to an instance of an object.
    Error
    1628
     These errors occured when various items were selected in LELA and after reboot on reinstall. And by the way LELA would be blank with no Network Map present. If you go through the log files under the Documents and Settings\All Users\Application Data\Pure Networks and C:\Documents and Settings\All Users\Application Data\Linksys\Lela, then search for the word fail, you will turn up these errors in bits and parts. The registry key:  4CDCB1A1-87EE-49AB-9A9F-E270FC5DB823 led me to the Pure Networks program or I might not have figured it all out.
    All of these error messages are related to the log files in either folder indicated above. 
    I hope this helps everyone - again the support was pitiful and I really expected more.

     The Linksys Link Network Advisor (LELA) sometimes works, most of the times does not on our "House-PC"; we have to install the disk again when it gets stuck to make it work. Also, in order to make changes to our network, we can do it easily on its web site, but the LELA will not synchronize it sometimes; so we have to go again and put the disk in to re-install LELA and "synchronize" it; though in reality, it is as if we are installing LELA for the first time, everytime we want to make changes to our network, by the way, a real pain!! After reading the advice above, I also installed Sisco's (the Linksys parent company) Network Magic software and now all my computers in my network work seamessly, and perfectly well. I can even share my printers now!! Thanks for this advice; very helpful indeed.
    a happy network administrator

  • Object Ref Prof R/s tab not appearing in complaint Tx?

    Dear All,
    I added object ref profile in complaint transaction. But I am unable to see relationship tab at header or item. The same profile is working fine with Service order. But its not working in complaint transactions.
    Please suggest.

    Dear Arun
    Thanks for your valuable input. But pbm is if I use reference data tab then sold to party of the tx in which we are putting ref data and sold to party of ref data shoud be same..otherwise it will not allow to attach..
    Please suggest why relationship tab does not appear and is this product error?
    Thanks

  • Reading a CSV file and producing an array of objects

    Hi everybody,
    I am writing an application which will read a cvs file and produce an array of objects.
    Can any body help me to solve this problem?
    Thanks
    Finny

    Hello,
    Have you tried this link?
    http://ostermiller.org/utils/CSV.html

  • How to pass array of Object in A Procedure using OCCI.......

    I m also trying for How to pass Object to a procedureb using OCCI...
    Steps....
    1. I created A type.....
    2. Then I created a VARRAY using that Type.
    3.After that I have written An Procedure with object as a parameter..
    now using OCCI how do u bind the parameter with this . plz note that using OTT
    i have already created the class representation of above object type i.e class
    four Files Created 1> demo.h 2>registermapping.h
    3> demo.cpp 2>registermapping.cpp
    After I want to Pass the Values in A Vector...
    vctor<full_name *> vect;
    stmt=con->createStatement("BEGIN Add_Object(:1); END;");
    full_name *name1 = new full_name; //Giving the Error here Given below....
    name1->
    name1->
    Through name1 Which Function I will call in which I will Pass a String....
    like
    name1->readSQL("Sanjay"); Or I have to add a function......
    vect.push_back(name1);
    setVector(stmt,1,vect,"FULL_NAME");
    error C2259: 'FullName' : cannot instantiate abstract class
    can u plz suggest me Why this Error is Giving......?
    How to pass the data?
    setFirst_name() and setLast_name() this two function I will add in Demo.cpp which one created automativcally by Using OTT command.....or other way plz tell me Boss ....
    Can u lz Suggest me ASAP....

    hi Nishant ,
    What u have done Now I mm trying ....
    can u Plz Suggest me......
    How to pass and Array of Object in Procedure using OCCI... Doing....
    90% finished Two Error's Are Coming...
    1> If I create the Class then Data Not Inserting table......
    2> If I will create the Class through OTT command.......
    then U can't Instantiate Object It is DIsplying ,this is Abstract Class(PObject)...
    Beco'z the below Method is Not adding Automatically by OTT command which is Pure Virtual Function.....
    But I added this Function Still SAme Error Giving..
    getSQLTypeName(oracle::occi::Environment env, void *schName,
    unsigned int &schNameLen, void **typeName,
         unsigned int &typeNameLen) const
    Plz Suggest me....
    regard's
    sanjay

  • Array of Object

    How to create array of object dynamically and the class is also having constructor.
    like:
    class Cir{
    private double radius;
    Cir(double r){
    redius=r;
    10 objects are to be created within for loop

    Cir c[]=new Cir[10]
    for(int i=0;i<10;i++)
    c [ i ] =new Cir(radious);
    Message was edited by:
    ramireddi

  • Array of objects.....different syntax !!

    Both are Array of objects.........
    Object[] array  = new Object[2];
            array[0] = new Long( 1 );
            array[1] = new String( "My string" );Another code.........
    private Color colors[] =
             { Color.black, Color.blue, Color.cyan, Color.darkGray,
             Color.gray, Color.green, Color.lightGray,
             Color.magenta, Color.orange, Color.pink, Color.red,
         Color.white, Color.yellow };Both are array of objects. but look the difference one usues new another dont
    i dont like the second one.....but it is usued. what is it ?

    What I meant is you can always use the new operator to create an array. You can even use it in conjunction with populating it: Object[] = new Object[] {"foo", new Integer(5), etc...}; But more to the point, declaring an array final says nothing about that array's elements.
    public class ZZZ {
        final int[] arr_; // legal, as long as all ctors give this variable a value
        public ZZZ() {
            arr_ = new int[1]; // legal, even without providing a value for the element
        public ZZZ(int size) {
            arr_ = new int[size]; // legal
            arr_[0] = 0; // legal
            arr_[0] = 1; // legal
    }

  • Calling a Procedure which has Array of Objects as arguments (from BPEL)

    Hi,
    I wanted to pass multiple records as arguments to a stored procedure from BPEL.
    We created stored procedure which takes array of Objects as arguments. I invoked it from BPEL. It was successfully compiled and deployed.
    At runtime it is throwing following error.
    <bindingFault xmlns="http://schemas.oracle.com/bpel/extension">
    <part name="code">
    <code>17072</code>
    </part>
    <part name="summary">
    <summary>Error binding the value of a parameter. An error occurred when binding the value of parameter ARG in the SCOTT.TESTPACK.TESTPROC API. Cause: java.sql.SQLException: Inserted value too large for column: "sadfsafsad" Check to ensure that the parameter is a valid IN or IN/OUT parameter of the API. Contact oracle support if error is not fixable.</summary>
    </part>
    <part name="detail">
    <detail>Inserted value too large for column: "sadfsafsad"</detail>
    </part>
    </bindingFault>

    I think you from Sierra Atlantic and you using Beta 3. There was a bug in Beta 3 in using arrays, which got fixed in post Beta3. You got to wait till next release.

  • Placing an array of objects onto stage

    I am trying to place an array of objects onto a stage where they drop vertically. I have been able to do it by placing the array objects into an object called "bag" but have found that the bag object only contains the last array object id so I can not apply actions to various array objects.
    Also my objects do not loop and only appear once.
    Below is the code so far.
    var tempArray:Array = new Array(); // Stores randomised values
    var bagArray:Array = new Array("gslow_id","gshigh_id","glow_id","ghigh_id","gdiv_id",
      "gcall_id","gbust_id","gbull_id","gboom_id","gbear_id"); // List of bag names
    function createBags() {
    if (tempArray.length == 0) { // check if array is empty
         for (var i:Number = 0; i < targets; i++) { // for loop - creat variable bagName to the value of targets
         var bagName: String = bagArray[i];
         var depthLevel:Number = this.getNextHighestDepth();
         // attach movies to time line
         this.attachMovie(bagName, bagName, depthLevel, {_x:random(350) + 100, _y:random(0) + spacing});
         spacing += 45;
         tempArray.push(bagName);
         //trace(tempArray);
         bag = _root[bagName]; // create a bag object contain the bagName variable
         //trace (bag);
         bag.onEnterFrame = function() {
              if (this._x < 570 && this._y > 0) {
              this._y += speed * random(8);
              } else {
              this._x = random(500);
              } // end if (this._x < 570 && this._y > 0)
         } // end bag.onEnterFrame ()
    bag.onPress = function() {
    // if bag is pressed select action
    //trace (bag); 
    xPos = this._x
    yPos = this._y
    unloadMovie(this);
    score += 1000
    scoreText_txt.text = score;
    //trace(score);
    checkScore();
    } // end bag.onPress ()
    //trace(targets);
    //trace(bagName);
    } // end for (var i:Number = 0; i < targets; i++)
    } // end if (tempArray.length == 0)
    } // End createBags()

    try:
    var bagA:Array=[];
    var bagArray:Array = new Array("gslow_id","gshigh_id","glow_id","ghigh_id","gdiv_id",
      "gcall_id","gbust_id","gbull_id","gboom_id","gbear_id"); // List of bag names
    function createBags() {
    if (tempArray.length == 0) { // check if array is empty
         for (var i:Number = 0; i < targets; i++) { // for loop - creat variable bagName to the value of targets
         var bagName: String = bagArray[i];
         var depthLevel:Number = this.getNextHighestDepth();
         // attach movies to time line
         var bag:MovieClip = this.attachMovie(bagName, bagName, depthLevel, {_x:random(350) + 100, _y:random(0) + spacing});
      bagA.push(bag);
         spacing += 45;
         //trace (bag);
         bag.onEnterFrame = function() {
              if (this._x < 570 && this._y > 0) {
              this._y += speed * random(8);
              } else {
              this._x = random(500);
              } // end if (this._x < 570 && this._y > 0)
         } // end bag.onEnterFrame ()
    bag.onPress = function() {
    // if bag is pressed select action
    //trace (bag); 
    xPos = this._x
    yPos = this._y
    unloadMovie(this);
    score += 1000
    scoreText_txt.text = score;
    //trace(score);
    checkScore();
    } // end bag.onPress ()
    //trace(targets);
    //trace(bagName);
    } // end for (var i:Number = 0; i < targets; i++)
    } // end if (tempArray.length == 0)
    } // End createBags()

  • Creating a generic class with a constructor that takes an array of objects

    I am relatively new to java and want to build a quick utility class that can generate a Run Length Encoding of any object. The idea is to take an array of objects of type "O" and then encode a string of objects that are "equal" to each other as an integer that counts the number of such equal instances and a single copy of the instance. This has the potential to very quickly reduce the size of some objects that I want to store. I would like to implement this class as a generic.
    public class RunLengthEncoding<O> {
         private class RLEPair {
              private int length;
              private O object;
         public RunLengthEncoding(O[]) {
    }As you can see, I need to make a constructor that takes an array of type "O". Is this possible to do? I can't seem to find the right syntax for it.
    Thanks,
    Sean

    Sorry. Obvious answer:
    public RunLengthEncoding(O[] oarray) {Again, sorry for the noise.

  • How to list an array of objects using struts in jsp and ActionForm

    I am using the struts ActionForm and need to know how to display an Array of objects. I am assuming it would look like this in the ActionForm:
    private AddRmvParts addRmv[];
    But I am not sure how the getter and setter in the ActionForm should look. Should it be a Collection or an Iterator?
    I am thinking I need to use an iterator in the jsp page to display it.
    I am also wondering if the AddRmvParts class I have can be the same class that gets populated by the retrieval of data from the database. This class has 10 fields that need to display on the jsp page in 1 row and then multiple rows of these 10 fields.
    Thanks.

    Most probably the easiest way to make it accessible in your page is as a collection.
    ie
    public Collection getAddRmvParts()
    You can use the <logic:iterate> or a <c:forEach>(JSTL) tag to loop through the collection
    As long as the individual items in the collection provide get/set methods you can access them with the dot syntax:
    Example using JSTL:
    <c:forEach var="addRmvPart" items="${addRmvParts}">
      <c:out value="${addRmvPart.id} ${addRmvPart.name} ${addRmvPart.description}"/>
    </c:forEach>

  • Thread use to find max and min in an array of objects??

    Hello everyone,
    I need to find the min and max int value in a array of Objects.
    This has to be done using threads--like divide the entire array into 10 or so blocks and find the local min and max in each block., Each block is run on a thread and finally comparing them to find the global max and min.How should I do this? I am new to Java programming and in particular to threads.
    Thanks for your time and patience in answering this newbie question.
    JP

    Hi,
    if i understand your problem, you have a big array with a lot of int values and you need to create a few arrays with a part of the big one in each, next each in a thread find the max and the min, next return the max and the min of each thread and compare these max and min to obtain the globals max and min?
    In that case you can create a class in which is your big array. you create a second class implementing Runnable, in its creator you put the instance of the
    first class and 2 int which are the beginning and the ending index. in this class add a method run in this method you create a loop to compare the current value to the max and min values, and you replace if you need to do. In the first class you put the main where you create a few instance of the second class in a thread :
         private Thread threadName = new Thread(new SecondClass(this, start, end));
    Next you start all these thread:
    threadName.start();
    At the end of the run method of the second class you have to write your result in the max and min fields of the first class(int type, you have to create it)
    Write it only if it's necessary (if the current max is > than the already existing max).
    I think it's complete!
    Sorry if it's not really easy to understand, I'm french, but you can answer if you have more questions.
    S�bastien

Maybe you are looking for