This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets 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
Author

Assigning values to objects in object array

expired user
Greenhorn

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.
Regards,
Manfred.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Assigning values to objects in object array
 
Similar Threads
Code not working...
GC help needed
Sun Cirtification
why doesnt char[] c=(char[]) arrayOfShorts work?