Discuss Add method of an array in the Java Help forum on Dev Shed. Add method of an array Java Help forum discussing all Java platforms - J2ME, J2SE and J2EE - as well as relevant standards, APIs and frameworks such as Swing, Servlets, JSPs, Applets, Struts, Spring, Hibernate, ANT, EJB, and other Java-related topics.
Receive the tools necessary to be the rock star of your field. Our 12-month program teaches you the evolving world of multi-channel marketing as well as the complex issues and opportunities found in the industry.
ASP Free and Iron Speed Designer are giving away $5,500+ in FREE licenses. Iron Speed's RAD CASE toolset can save up to 80% of your coding time. One free license per week, one perpetual license per month! Download and Activate to enter!
Web development can be a daunting task, even for specialists. There is a lot of information to absorb and a lot of technologies to learn in order to manage a superior website. When trying to learn the ropes, developers need a reliable source to introduce new ideas that can be easily implemented. When working on large projects, even web veterans may run into a technology or an aspect of a technology that they are unfamiliar with.
Posts: 1,758
Time spent in forums: 1 Week 20 h 51 sec
Reputation Power: 288
Your question leaves many things undefined and unanswerable.
What class is the box variable? Does it have an add() method? Where does the add method put the value that is passed to it?
Where are the variables: item1 and item2 defined?
Quote:
how do i initialize the item array in the box class?
You should initialize the variable: array before you put it into the box. If array has a null value that is what the box's add() method will receive.
Posts: 1,758
Time spent in forums: 1 Week 20 h 51 sec
Reputation Power: 288
That looks like a start.
Also you need to define the array and give it some slots so you can add to it.
Your constructor sets the array to null instead of defining it with some size.
Why not define an array with some empty slots so you will be able to put items into it in the add method?
Posts: 1,758
Time spent in forums: 1 Week 20 h 51 sec
Reputation Power: 288
Code:
box = new Box[numItems+1];
This replaces the existing array with a new array. The contents of the old array is lost.
You can not change the size of an array. You must create a large enough one in the constructor. The add method should add items to the existing array.
If the array is full when add is called, then add must create a new larger array, copy the contents of the existing array to it and replace the existing array with the new array.
You must post the code that you are compiling. The code you have posted so far does not make sense. The variable names and the class names are changing from post to post.
Last edited by NormR : January 29th, 2012 at 09:07 PM.