• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with linked list  RSS feed

 
tan kian
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all, i'm having a bit of trouble with this code, what i want it to do is just return a string array of strings where possible, its ok if the string array is empty when returned, since there are situations in my project where its supposed to be empty. I keep getting either a IndexOutOfBounds Exception or a NullPointerException when i return the string array. Can anyone help?

class InfoLib
{
String data;
InfoLib next;
public InfoLib(String data)
{
this.data = data;
this.next = null;
}
}

public String[] getallinfo()
{
//this is here to initialise the string array
String[] summary = new String[0];

//count is a global to be passed in
if (count > 0)
{
summary = new String[count];
int x = 0;
//assigns a link list head, and traverse through the
//list and get info
InfoLib llhead;

if (! isEmpty())
{
while (llhead.next != null)
{
summary[x] = llhead.data;
llhead = llhead.next;
x = x + 1;
}
summary[x] = llhead.data;
}
}
return summary;
}
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A couple pointers first. Using the [ code ] ... [ /code ] UBB blocks will preserve the formatting and indentation of code blocks. Remove the spaces above or use the helpers below the edit box.

The problem is that you do not initialize the local llhead reference before iterating through the list. This causes the NullPointerException when the list is not empty.While not mandatory, it's typical to create two classes for the linked list: one represents a node in the list as your InfoLib does and the other represents the list itself and holds a reference to the head node, or null if empty.

As for the ArrayIndexOutOfBoundsException, I assume you're accessing the array after it's returned without checking its length. If summary.length returns 0, you cannot access any elements without an exception.
 
tan kian
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah, i never checked for the length of the array before returning it, cause i do all my checking before the return statement. so.........there's no way i can get past the problem? =( the list needs to be empty at times...
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by tan kian:
there's no way i can get past the problem? =(

No no, since you return a zero-length array instead of null, you can test it after it's returned.
 
tan kian
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok, thanks =)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!