Why foreach loop gives array elements but for loop gives address instead of elements? In java

huangapple go评论57阅读模式
英文:

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 &lt; 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 &lt; 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 &lt; z.length; i++) {
        System.out.println(z[i]);
    }

huangapple
  • 本文由 发表于 2023年2月8日 11:03:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定