栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java:String数组(对象)、for-each循环

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java:String数组(对象)、for-each循环

String变量

当String变量没有初始值的时候,默认为null,输出也为null,String类型的数组也一样。

public static void main(String[] args) {
		int[] ia = new int[10];
		String[] a = new String[10];
		System.out.println(ia[0]+2);
		System.out.println(a[0]+2);
		System.out.println(a[0].length());
	}

String类型的数组和String类型一样,不是本身数据的拥有者,只是数据的管理者,String类型的变量会指向一个存储对应数据的地方,而String类型的数组可以理解为多个String类型的变量,指向多个地址。

for-each循环

int类型的数组通过for-each循环,无法修改值

public static void main(String[] args) {
		int[] ia = new int[3];
		for(int i=0; i
			ia[i] = i;
		}
		for(int k:ia )
		{
			System.out.println(k);
			k = 0;
		}
		for(int k:ia )
		{
			System.out.println(k);
		}
0
1
2
0
1
2

而对象数组,可以通过for-each循环修改值

class Value
{
	private int i;
	public void set(int i) {this.i = i;}
	public int get() {return i;}
}
public class test {
	
	public static void main(String[] args) {
		Value[] a = new Value[3];
		for(int i=0; i
			System.out.println(a[i]);
			a[i] = new Value();
			a[i].set(i);
		}
		for(Value v : a )
		{
			System.out.println(v.get());
			v.set(0);
		}
		for(Value v : a )
		{
			System.out.println(v.get());
		}
null
null
null
0
1
2
0
0
0

如上代码,Value类型的数组a的每一个元素都是一个Value类型的对象,每一个元素都可以调用对象的成员函数[get()|set()]。
int类型的for-each相当于将int类型数组中的一个元素赋值给对应的变量(v)。

而String类型的数组是数组的管理者而不是所有者,相当于将管理对应元素的指针给了(v)一份,v和数组中的指针都指向同一个元素,所以可以用v.get()改变String类型的数组元素。


在String数组的for-each循环中,v第一轮指向String数组第0个元素指向的那个数据,将其修改为0,第二轮指向第一个元素指向的那个数据,将其修改为0。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/851789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号