关于迭代器的一个问题 请大神说说。。。。。。。。。。。。。。。

woshiyeda 2014-11-22 05:39:36
public static void main(String[] args) {


List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Iterator it = list.iterator();
while (it.hasNext()) {
Integer a = (Integer) it.next();
a =123;
System.out.println(list.get(0));

}

我想通过迭代器改变里面的值,我的认为是我通过迭代器迭代出来 并赋给a ,因为集合装的是对象,所以我认为a指向的是集合元素的地址,所以我希望通过a的改变来改变集合元素的值, 但是始终不行,我想问问为什么 ?谢谢
...全文
167 5 打赏 收藏 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
WANG774943512 2014-11-22
  • 打赏
  • 举报
回复
iterator迭代的时候不允许修改集合,想修改集合用ListIterator。
_reason 2014-11-22
  • 打赏
  • 举报
回复
这是一个关于包装类的问题。 下面的代码详细的解释了你的疑问 (顺便优化了一下代码):

import java.util.*;
public class TestAtuoBox{
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		Collections.addAll(list,1,2,3);
		System.out.println(list);

		/////////////////////////////////////////////////////
		Integer num1 = new Integer(1);// 不同于Integer num1 = 1; 我的这句涉及到常量池取值以及自动打包
		Integer num2 = num1;
		System.out.println(num1 == num2);
		// 从JDK5.0开始 基本数据类型和包装类类型之间可以直接赋值[自动打包 自动解包]
		// 下面的这行代码创建了一个新变量,原因如下
		num2 = 2; // 等同于执行了 num1 = Integer.valueOf(2); 自动打包[@since JDK 5.0]
		System.out.println("num1是:" + num1 + " num2是:" + num2);
		/////////////////////////////////////////////////////

		System.out.println("------------------------------");
		for(Iterator<Integer> car = list.iterator(); car.hasNext(); ){
			Integer a = car.next(); // 相当于上面的 Integer num2 = num1;
			a = 123; // 相当于上面的 num2 = 2;
			// 没明白下面是什么意思。如果想遍历List集合,不如用foreach或迭代器
			System.out.println(list.get(0));
		}
	}
}
AceShot 2014-11-22
  • 打赏
  • 举报
回复
引用 2 楼 woshiyeda 的回复:
[quote=引用 1 楼 Mr_WangB 的回复:] a又指向123的地址了吧
a之前指向的是每一个元素,我想的是他改变了 那么元素就应该改变 因为是同一个地址[/quote] a 可以说存的是地址,a原来是指向每个元素的,但是后来a =123;使得a指向了新的Integer对象,此时仅仅是a的值发生了变化,但a原来指向的list中的对象还是没变化的。总之,就是a指向了不同地方(存的地址变了),但所指向的对象都没变。
woshiyeda 2014-11-22
  • 打赏
  • 举报
回复
引用 1 楼 Mr_WangB 的回复:
a又指向123的地址了吧
a之前指向的是每一个元素,我想的是他改变了 那么元素就应该改变 因为是同一个地址
mr_wangb 2014-11-22
  • 打赏
  • 举报
回复
a又指向123的地址了吧

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧