This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes add and remove method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "add and remove method" Watch "add and remove method" New topic
Author

add and remove method

Aditya Herlambang
Greenhorn

Joined: Feb 01, 2007
Posts: 11
I am asked to create an add method with the following rules:
When adding new elements, check to ensure there is room in the array data. If there is no unused array index, grow the array by delta elements. When removing existing elements, shrink the array by delta elements whenever there is room to add more than delta elements. In other words, leave no more than delta empty array locations at any time. The array must have from 0 through delta empty indexes at all times. The following assertions must pass.

This add method must work for any data type. And so far the method that I have create is:

The problem with this code is that when I try to add an interger it always gives me a null point exception because all the value in the array are set as null the very first time, how do I get this method to work the way it's suppose to be??>

EDIT by mw: Added Code Tags.
[ February 03, 2007: Message edited by: marc weber ]
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30795
    
157

Aditya,
A common technique for this is to write
element.equals(data[i])
instead of
data[i].equals(element)

Since you know that element isn't null the former won't throw an exception. As an alternative you can write
if (element != null || data[i].equals(element))


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Aditya Herlambang
Greenhorn

Joined: Feb 01, 2007
Posts: 11
okay here's what I got for the add method:




is this right according to the rules above?? thanks
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30795
    
157

Almost.


Something is mismatched in this snippet. If data[i] is null, wouldn't you want to set the element to data[i] rather than data[n] ?
Aditya Herlambang
Greenhorn

Joined: Feb 01, 2007
Posts: 11
I think it's right data[n] because I declare another variable called n which will count the number of data in an array, so there will be no skipping the array by using this.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: add and remove method