Java对于每个循环对象分配均不起作用 [英] Java For each loop object assignment is not working
本文介绍了Java对于每个循环对象分配均不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
公共类A {int val;公开A {int val} {this.val = val;}公共无效print(){System.out.println(val);}公共静态void main(String args []){A [] aList =新的A [10];int temp = 1;for(A a:aList){a =新的A(temp ++);}for(A a:aList){打印();;}}}
在A.main的线程"main"中获取异常java.lang.NullPointerException(A.java:28)aList地址空间A类对象已存储,但是再次迭代无法获取存储的对象,这些对象存储在哪里?
解决方案
a
是for循环的局部变量,因此分配给它不会影响aList数组的元素./p>
您应该使用常规的for循环来初始化数组:
for(int i = 0; i< aList.length; i ++){aList [i] =新的A(temp ++);}
public class A{
int val;
public A(int val){
this.val = val;
}
public void print() {
System.out.println(val);
}
public static void main(String args[]){
A[] aList = new A[10];
int temp =1;
for(A a : aList){
a = new A(temp++);
}
for(A a : aList){
a.print();;
}
}
}
Getting Exception in thread "main" java.lang.NullPointerException at A.main(A.java:28) aList address space Class A objects are stored but again iterate unable to get stored objects, where are the objects stored ?
解决方案
a
is a local variable of the for loop, so assigning to it doesn't affect the elements of the aList array.
You should use a regular for loop to initialize the array :
for(int i = 0; i < aList.length; i++){
aList[i] = new A(temp++);
}
这篇关于Java对于每个循环对象分配均不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文