Java中集合list的add方法添加的不是值COPY而是地址
2016-07-30 22:26
549 查看
测试代码如下:
package test;
import java.util.ArrayList;
import java.util.List;
class Point {
int x;
int y;
public Point(int x,int y)
{
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
public class TestListAdd {
public static void main(String[] args)
{
List<Point> storePointList = new ArrayList<Point>();
Point testPoint = new Point(3,4);
storePointList.add(testPoint);
System.out.println("x = " + storePointList.get(0).getX() + ", y = " + storePointList.get(0).getY());
testPoint.setX(8);
System.out.println("x = " + storePointList.get(0).getX() + ", y = " + storePointList.get(0).getY());
}
}
结果为:
x = 3, y = 4
x = 8, y = 4
也即:
在add进storePointList之后,修改原来的testPoint 中的值,仍将改变storePointList中对应元素的值,可以看出add中()的只是传地址。
在这一点上和一般的java方法传参是一致的。一般java传参传的同样是地址。
可以总结出一个规律:在java中凡是对对象(或者说对象名)进行的传参传的都是地址。这是在方法体内部通过传进来的参数更改其下的属性可行的。
package test;
import java.util.ArrayList;
import java.util.List;
class Point {
int x;
int y;
public Point(int x,int y)
{
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
public class TestListAdd {
public static void main(String[] args)
{
List<Point> storePointList = new ArrayList<Point>();
Point testPoint = new Point(3,4);
storePointList.add(testPoint);
System.out.println("x = " + storePointList.get(0).getX() + ", y = " + storePointList.get(0).getY());
testPoint.setX(8);
System.out.println("x = " + storePointList.get(0).getX() + ", y = " + storePointList.get(0).getY());
}
}
结果为:
x = 3, y = 4
x = 8, y = 4
也即:
在add进storePointList之后,修改原来的testPoint 中的值,仍将改变storePointList中对应元素的值,可以看出add中()的只是传地址。
在这一点上和一般的java方法传参是一致的。一般java传参传的同样是地址。
可以总结出一个规律:在java中凡是对对象(或者说对象名)进行的传参传的都是地址。这是在方法体内部通过传进来的参数更改其下的属性可行的。
相关文章推荐
- Java中集合list的add方法添加的不是值COPY而是地址
- Java中集合list的add方法添加的是地址(引用)不是值
- Java 集合之List 集合的添加方法顺序分析以及add和addAll区别
- 继承List<T>类,并且完成List的Add()(在集合的末尾添加)方法和Get()(通过索引的方式获取)方法。并且写出方法的时间复杂度。
- java中copy 一个list集合的方法
- Java中对对象的操作是引用操作-建立Temp对象是,应该在循环里面new一个新的地址,再使用add添加到集合中去
- List.add方法——向集合列表中添加对象
- Java中用list的add方法添加数据时,报空指针异常
- list的add方法 ,foreach循环添加map---List.add(map)(通过一个java爬虫案例说明)
- Java中list集合的交集和差集的用法和如何将数组转换为集合的方法
- JAVA基础回顾1 遍历List Set 和Map集合的所有方法
- 用Java集合中的Collections.sort方法对list排序的两种方法
- Java:集合,对列表(List)中的自定义对象按属性(字段)排序(正序、倒序)的方法
- 用Java集合中的Collections.sort方法对list排序的两种方法
- java中去除List集合中重复数据的方法
- 使用 AddRange 方法将多个 ListItem 对象添加到集合
- 黑马程序员:Java基础——List集合共性方法,Iterator迭代和集合具体对象的特点
- [黑马程序员]集合_回头看List的add方法
- (好使)用Java集合中的Collections.sort方法对list排序的两种方法
- java中调用存储过程并传递list集合参数的方法