Multidimensional Array to Set

steelodon

Senior member
Oct 29, 2007
586
13
81
Set<String> PropType = new HashSet<String>();

for (int j = 0; j < cols; j++){
PropType.add(line[1][j]);
}

Iterator Prop = PropType.iterator();

while(Prop.hasNext()){
System.out.print(Prop.next());
}

Tried to run this code...but it keeps giving the error:

Exception in thread "main" java.lang.NullPointerException

Any suggestions?
 

purbeast0

No Lifer
Sep 13, 2001
53,764
6,645
126
im guessing since you left other code out that it is happening somewhere else.

that code you have there looks like it shouldn't throw any null pointer exception.

when you get the exception, look at the thread stack and it will give you a line number and file where the null pointer exception happens.
 

TheRyuu

Diamond Member
Dec 3, 2005
5,479
14
81
Probably time to show the debugger a little love. ;)

With the visual debugging tools in Eclipse or Netbeans it should make it a breeze.
 

Net

Golden Member
Aug 30, 2003
1,592
3
81
if your sure its from this block of code then it would be this line

PropType.add(line[1][j]);

being evaluated as

PropType.add(null);
 

purbeast0

No Lifer
Sep 13, 2001
53,764
6,645
126
if your sure its from this block of code then it would be this line

PropType.add(line[1][j]);

being evaluated as

PropType.add(null);

you can add a null value to a hashset and it won't throw an exception.
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,836
4,815
75
right, but if line[1] doesn't exist [j] will throw.

Say, given that, the first loop could be replaced by:

Code:
[spoiler]Set<String> PropType = new HashSet<String>(Arrays.asList(line[1]));[/spoiler]

Couldn't it? (Code in spoiler in case this is homework or something.)
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
pretty sure that will throw an index out of bounds exception, not a null pointer exception.

What if you set lines[1] = null? Maybe I wasn't quite clear, but if its possible to put a null in the collection it's also possible to get one out. Setting index 1 to null is different than never setting index 1.
 

purbeast0

No Lifer
Sep 13, 2001
53,764
6,645
126
What if you set lines[1] = null? Maybe I wasn't quite clear, but if its possible to put a null in the collection it's also possible to get one out. Setting index 1 to null is different than never setting index 1.

ah yea gotcha, that makes sense. that would definitely toss out a null pointer exception.

which makes me wonder why he didn't post the rest of his code along with this error.
 

iCyborg

Golden Member
Aug 8, 2008
1,388
94
91
I wonder why he didn't post more of the stack backtrace. Usually the next few lines are far more revealing...