英文:
Why foreach loop gives array elements but for loop gives address instead of elements? In java
问题
I tried to print all the elements in an array using both for loop and foreach loop.
In for loop, I got addresses of elements instead of elements themselves. But by using for loop I got the elements themselves. So how this is working even I didn't override toString method also but am getting elements!!
public class ArrayReturn {
public static int[] Multi(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * 2;
}
return a;
}
public static void main(String[] args) {
int ar[] = {2, 3, 4, 5, 6, 7};
int z[] = Multi(ar);
for (int i = 0; i < z.length; i++) {
System.out.println(z);
}
for (int i : z) {
System.println(i);
}
}
}
OUTPUT
[I@5a07e868
[I@5a07e868
[I@5a07e868
[I@5a07e868
[I@5a07e868
[I@5a07e868
4
6
8
10
12
14
I expected either address from both loops or elements. But I got an address in the for loop and elements in the foreach loop.
英文:
I tried to print all the elements in an array using both for loop and foreach loop.
In for loop, I got addresses of elements instead of elements themselves. But by using for loop I got the elements themselves. So how this is working even I didn't override toString method also but am getting elements!!
public class ArrayReturn {
public static int[] Multi(int []a)
{
for (int i = 0; i < a.length; i++) {
a[i] = a[i]*2;
}
return a;
}
public static void main(String[] args) {
int ar[] = {2,3,4,5,6,7};
int z[] = Multi(ar);
for (int i = 0; i < z.length; i++) {
System.out.println(z);
}
for (int i : z) {
System.out.println(i);
}
}
}
OUTPUT
[I@5a07e868
[I@5a07e868
[I@5a07e868
[I@5a07e868
[I@5a07e868
[I@5a07e868
4
6
8
10
12
14
I expected either address from both loops or elements. But I got address in for loop and elements in foreach loop.
答案1
得分: 0
如其他人已经告诉你的,在你的for循环中,你正在打印数组z,所以出于这个原因,它打印了<del>对象地址</del>你所看到的内容。如果你想打印每个位置存储的值,你需要使用for循环的索引。
for (int i = 0; i < z.length; i++) {
System.out.println(z[i]);
}
英文:
As others have told you, in your for loop you're printing the array z, so for that reason it's printing <del>the object address</del> what you're seeing. If you want to print the value stored in each position, you have to use the for loop's index.
for (int i = 0; i < z.length; i++) {
System.out.println(z[i]);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论