Y
Y
Yaroslav Vorontsov2016-05-24 22:50:24
Java
Yaroslav Vorontsov, 2016-05-24 22:50:24

How to properly create an array of objects in java?

There is a code:

@Override
        public void run() {
            sprite = new Sprite(this, man);
            for(int i = 0; i < colvo; i++){
                meteor[i] = new Meteor(this, meteorit);
            }
            while(update){
                if(!holder.getSurface().isValid()) {
                    continue;
                }
                Canvas c = holder.lockCanvas();
                onMyDraw(c);
                holder.unlockCanvasAndPost(c);
            }
        }

Everything is fine with the Meteor class, if, for example, I create instances of the class separately, everything will work fine, but as soon as I try to do everything humanly and put the instances in an array, a NullPointerException is thrown, which points specifically to this line
meteor[i] = new Meteor(this, meteorit);
: mention that all this happens inside a class
public class MySurfaceView extends SurfaceView implements Runnable{...}

Which in turn is inside the class
public class MainActivity extends Activity implements View.OnTouchListener{...}

In short, I can’t create a seemingly normal array of objects, but I can’t create instances of a class individually.
Thank you very much in advance for your help, I'm at a loss.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
G
GavriKos, 2016-05-24
@GavriKos

If only you could see how meteor is declared... Most likely you didn't make new to it (the array).
You can also use ArrayList.

A
Andrey Shishkin, 2016-05-25
@compiler

No one uses arrays directly, well, only in some exotic cases. Use collections. ArrayList is fine for you.

G
guras256, 2016-05-24
@guras256

the problem is obvious - the meteor array is null
and it's not very clear why the array
is why not do it like this:

List<Meteor> meteors = 
    Stream.generate(() -> new Meteor(this, meteorit))
        .limit(colvo)
        .collect(Collectors.toList())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question