Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

add and remove method

 
Aditya Herlambang
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33694
316
Eclipse IDE Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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))
 
Aditya Herlambang
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33694
316
Eclipse IDE Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic