Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array of Vectors - null pointer exception

 
karl holmgren
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am getting a null pointer exception for the last line of code, why? Am I not allowed to put Vector objects in arrays?

import java.util.*;

private int noCh=1;
private Vector channels[];
.
.
.
private channels = new Vector[noCh+1];
.
.
.
if(channels[ch].size()>=sample && sample>-1){.....}

Thanks!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by karl holmgren:
I am getting a null pointer exception for the last line of code, why? ...

I would need to see more of the code, but my guess is that channels[ch] is simply referencing a null value at some point (that is, there's no Vector object at the array index).
[ October 11, 2005: Message edited by: marc weber ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Karl,

Welcome to JavaRanch!

You are indeed allowed to put Vectors into arrays. Java is complaining because you haven't done so! The line

private Vector channels = new Vector[noCh+1];

allocates an array of Vector variables -- i.e, references to Vectors. There are no Vectors in the array, though -- all those variables are null. You have to actually allocate the Vectors:



Then you can call size() on them.

If this is confusing you, have a look at this and this.
[ October 11, 2005: Message edited by: Ernest Friedman-Hill ]
 
karl holmgren
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the great answers!

When I fill the arrays with empty Vectors it works.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic