开发者

Within an array of objects can one create a new instance of an object at an index?

Here's the sample code:

class TestAO 
{ 
    int[] x; 

    public TestAO () 
    {
        this.x = new int[5] ;
        for (int i = 0; i<x.length; i++)
        x[i] = i; 
    } 

    public static void main (String[]arg) 
    { 
        TestAO a = new TestAO ();
        System.out.println (a) ;        
        TestAO c = new TestAO () ; 
        c.x[3] = 35 ; 
        TestAO[] Z = new TestAO[3] ; 
        Z[0] = a ;
        Z[1] = (TestAO b = new TestAO()) ; 
        Z[2] = c ; 
    } 
}

When I try to compile this I get an error message at the line Z[1] which reads as follows:

TestAO.java:22: ')' expected
        Z[1] = (TestAO b = new TestAO()) ; 
                       ^

What I'm trying to do here is create an instance of the object TestAO that I want to be in that index withi开发者_开发知识库n the assignment of the value at that index instead of creating the instance of the object outside of the array like I did with a.

Is this legal and I'm just making some syntax error that I can't see (thus causing the error message) or can what I'm trying to do just not be done?

EDIT:

in regard to Mark's answer here is my follow up question:

is there a shorter way to assign values to the instance variables of an object in the array of objects than this: (without writing any special constructors)

    Z[1] = new TestAO() ; 
    Z[1].x[4] = 80085 ;


It's easier than you think:

Z[1] = new TestAO(); 


Declaring variable like this is impossible. Just write "Z[1] = new TestAO();" and if you want another reference "TestAO b = Z[1]";


What you're really doing here is assigning the result of an assignment to Z[1]. The return type of an assignment in Java is boolean, so the way you're doing it is not going to work.

Try:

Z[1] = new TestAO();


Try this:

Z[1] = new TestAO() ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜