File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Assigning values to objects in object array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Assigning values to objects in object array" Watch "Assigning values to objects in object array" New topic

Assigning values to objects in object array

expired user

Joined: Dec 13, 2001
Posts: 11

Java is not a structured language. It is object oriented and we lack the structurs in one or another way.
In C++, we can create an object array easily and can able to assign the variables so easily, even assigning the values of the member variables of an object array.
In java, we will encounter NullPointerException if we try to assign value to an member variable directly. The solution is to create a temporary object of that particular object and assign the values in to the temporary object. After this we can assign the temporary object into the array.
For example,
class OArray
int a;
char c;
class OArrayAccess
OArray o = new OArray; //temporary object
OArray[] oa = new OArray[10];
//assigning values in to the temp' object
o.a = 10;
o.c = 'k';
//assigning values in to object array
oa[0] = o;
//temp' object is assigned to the object array
In order to retrive the values, we have to again assign the array object in to a temporary object and access the values.
The thought of using the vector classes will help only when we deal with different instances of a class. In the case of same object in an oops environment, Object array is the only solution.

Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Kadirvelu,
Not sure if you are asking anything or just stating thoughts.
Here are some of my thoughts about what you have said.
1. Object arrays are limited in that you must define their size when they are declared. Vectors (and other Collections) can be dynically resized after it is declared.
2. Object arrays might require a temporary variable to assign them but not to retrieve them. We can place the following at the end of your code snippet:
System.out.println( oa[0].i + ", " + oa[0].c );
without a compiler error and it will run great.
I agree. Here's the link:
subject: Assigning values to objects in object array
It's not a secret anymore!