循环体内的变量提出来使用过程产生的疑问

boylove10 2018-04-04 06:41:01
代码:
ArrayList<ArrayList<Integer>> a=new ArrayList<>(0);
for(int i=0;i<2;i++)
{
ArrayList<Integer> a1=new ArrayList<>(0);
a1.add((Integer)1);
a.add(a1);
}
System.out.println(a);
//System.out.println(a1);//明明是访问不到的。
结果是[[1][1]]。
疑问:add()不是浅拷贝么?那么局部变量a1在退出for循环之后不是应该被销毁回收了?为什么还能访问得到数据?
求教:集合深拷贝在哪里?
...全文
373 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
boylove10 2018-04-05
  • 打赏
  • 举报
回复
就普通的能运行啊,结果也没错啊。java 版本1.8,工具 eclipse。
yjsl__ 2018-04-05
  • 打赏
  • 举报
回复
不能用C++的思想去看Java了

import java.util.HashMap;
import java.util.Map;

public class MapTest {

	public static void main(String[ ] args) {

		A a1 = new A(1);
		A a2 = new A(2);

		Map<Integer , A> map = new HashMap<Integer , A>();
		map.put(1 , a1);
		map.put(2 , a2);
		System.out.println(map);
		A a3 = map.get(1);
		a3.setX(0);// 修改有效
		System.out.println(map);

		Map<Integer , String> map2 = new HashMap<Integer , String>();
		map2.put(1 , "A");
		map2.put(2 , "B");
		System.out.println(map2);
		String str = map2.get(1);
		str = "C";// String类型比较特殊,修改无效
		str = str + str;
		System.out.println(map2);

		B b1 = new B("D");
		B b2 = new B("E");

		Map<Integer , B> map3 = new HashMap<Integer , B>();
		map3.put(1 , b1);
		map3.put(2 , b2);
		System.out.println(map3);
		B b3 = map3.get(1);
		b3.setB("F");// 这样就有效了
		System.out.println(map3);

		
	}

}

class A {

	int x;

	public A(int x) {

		super();
		this.x = x;
	}

	public int getX() {

		return x;
	}

	public void setX(int x) {

		this.x = x;
	}

	@Override
	public String toString() {

		return "A [x=" + x + "]";
	}

}

class B {

	String b;

	public B(String b) {

		super();
		this.b = b;
	}

	public String getB() {

		return b;
	}

	public void setB(String b) {

		this.b = b;
	}

	@Override
	public String toString() {

		return "B [b=" + b + "]";
	}

}
初尘19 2018-04-05
  • 打赏
  • 举报
回复
对象被引用着,肯定可以访问到啊
CrazyCoder1992 2018-04-05
  • 打赏
  • 举报
回复
建议去了解一下Java的回收机制,只有当一个对象失去所有引用的时候,才会对该对象进行回收。 a.add(a1) 这个操作使a1对象被a对象所引用,除非a被销毁,或者将a1从a中移除之前(即解除引用关系),对象a1才可能被回收。
oyljerry 2018-04-04
  • 打赏
  • 举报
回复
不应该能访问。按理语法都有问题。

51,410

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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