Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A vector of class instances

Status
Not open for further replies.

jlapointe

Programmer
Aug 22, 2005
2
0
0
CA
I'm fairly new to Java, and I'm having some troubles with a vector. Say I have something like this:

Code:
  class Blah {
      public int test;
      
      public Blah() {
        test=3;
      }
    }
    
    Vector v = new Vector(0,1);
    v.addElement(new Blah());
    
    
    int t = v.elementAt(0).test;
  
  
  }

It's all fine up to the last line, which gives me an error, telling me it can't find variable test.

Obviously I want each element of vector v to be an instance of blah, but why can't I reference instance variables this way? It works fine using an array instead of a vector, but that doesn't suit my purposes, unless I rework a bunch of stuff.
 
Hi,

It should be

Code:
((Blah)v.elementAt(0)).test

Cheers
Venu
 
In the future please post newbie/standard Java questions in forum269 - this forum is meant for J2EE questions only.

Your code has got several problems with it - for a start you have code outside of any method declarations. If you realise this, then in the future, please paste your [relevant] code *as is* rather than giving us an incorrect subset/retype of it.

Your actual problem with regards to your post is that you are not casting your vector object.

Try this :

Code:
  class Blah {
      public int test;
      
      public Blah() {
        test=3;
      }
    }

    public void someMethod() {
       Vector v = new Vector();
       v.addElement(new Blah());
       
       // Anything added into a vector is an "Object" class so you must cast it ...
       Blah b = (Blah)(v.elementAt(0));

       // once casted, you may access its members
       int t = b.test;

    }  
  
  }

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Venur,

If you are replying to questions that should be in the Java forum ( forum269 ), please can you direct the person to that particular forum for future posts.

I follow a general rule - if it is the person's first post in a Java-related forum, then I just mention it (as above) ; if they are a repeat "wrong-forum" poster, then I red-flag it for the admins to delete.

Cheers :)

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Oh ok, thanks a lot. Sorry about posting in the wrong spot, I'm obviously new to the forums.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top