• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Assigning values to objects in object array

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Power corrupts. Absolute power xxxxxxxxxxxxxxxx is kinda neat.
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic