Java 数组只读取,从不写入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19475447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:35:25  来源:igfitidea点击:

The array is only read from, never written to

javaarrays

提问by

Good morning, I create this class in java :

早上好,我用 java 创建了这个类:

public class MapPoint {          
    public MapPoint() {
      this.tag = new String() ;
      this.Id = 0 ;
    }

public long Id;
public double lon;
public double lat;
public String tag; 

}

but when I want to create an array of MapPointin my main function like this :

但是当我想MapPoint在我的主函数中创建一个这样的数组时:

public class mainTestClass {


    public static void main(String[] args){ 
       MapPoint[] mapPoints = new MapPoint[100];
       mapPoints[0].setId(2);
       System.out.println(mapPoints[0].Id);

   }
}

I have this hint

我有这个提示

"The array is only read from, never written to"

“数组只读取,从不写入”

and when I run my program I have this error :

当我运行我的程序时,出现此错误:

Exception in thread "main" java.lang.NullPointerException at mainTestClass.main(mainTestClass.java:34).

mainTestClass.main(mainTestClass.java:34) 处的线程“main”java.lang.NullPointerException 中的异常。

please help

请帮忙

thanks.

谢谢。

采纳答案by Alexis C.

You have just declared an array that can contains at most 100 MapPoint objects. Now, you need to create an object in the array.

您刚刚声明了一个最多可包含 100 个 MapPoint 对象的数组。现在,您需要在数组中创建一个对象。

mapPoints[0] = new MapPoint();
mapPoints[0].setId(2);

When you're doing MapPoint[] mapPoints = new MapPoint[10];it's like in this situation : enter image description here

当你这样做时MapPoint[] mapPoints = new MapPoint[10];,就像在这种情况下: 在此处输入图片说明

That's why you got a NullPointerException.

这就是为什么你有一个NullPointerException.

回答by Ankit Rustagi

Thats because you have to initialize the variable first.

那是因为您必须先初始化变量。

mapPoints[0] = new MapPoint().setId(2);

回答by Se Won Jang

When you create an array like:

当你创建一个数组时:

MapPoint[] mapPoints = new MapPoint[100];

You're not creating an array with 100 mappoints.

您不是在创建具有 100 个映射点的数组。

You're creating an array that has space to hold 100 reference to map points.

您正在创建一个数组,该数组有空间容纳 100 个对地图点的引用。

so You need to create a MapPoint yourself, and put it in the array.

所以需要自己创建一个MapPoint,放到数组中。