This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assigning values to objects in object array

 
expired user
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic