java 引用类型的数据传递的是内存地址
java中引用类型的数据,传递的是内存地址,像类,数组,接口,String等等都是引用类型!
看下面的代码和截图
public class Test2 {
// java中引用类型的数据传递的是内存地址
private Map<String, Student> students = new Hashtable<String, Student>();
public void myTest() {
Student student1 = new Student("令狐冲", 16, "华山派", 19888.66);
Student student2 = new Student("韦小宝", 15, "紫禁城", 99999.99);
Student student3 = new Student("张无忌", 18, "光明顶", 18888.88);
students.put("1", student1);
students.put("2", student2);
students.put("3", student3);
Iterator<Map.Entry<String, Student>> entries = students.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, Student> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
entry.getValue().setAge(entry.getValue().getAge() + 1);
}
}
public void myTest2(){
List<String[]> citys = new ArrayList<String[]>();
String [] cityNames = {"赣州市", "于都县", "江西省", "中国", "赣南地区"};
citys.add(cityNames);
for (int index = 0; index < citys.size(); index++) {
String[] mycityNames = citys.get(index);
for (int i = 0; i < mycityNames.length; i++) {
System.out.println(mycityNames[i]);
if (i == 1) {
//修改mycityNames数组 (java中引用类型的数据传递的是内存地址)
mycityNames[i] = "我们" + mycityNames[i];
}
}
System.out.println("--------------------------------");
for (int i = 0; i < mycityNames.length; i++) {
System.out.println(mycityNames[i]);
}
}
System.out.println("--------------------------------");
//修改cityNames数组 (java中引用类型的数据传递的是内存地址)
cityNames[0] = "我们赣州市";
for (int index = 0; index < citys.size(); index++) {
String[] mycityNames = citys.get(index);
for (int i = 0; i < mycityNames.length; i++) {
System.out.println(mycityNames[i]);
}
}
}
public static void main(String[] args) {
Test2 test2 = new Test2();
test2.myTest();
System.out.println("--------------------------------");
Iterator<Map.Entry<String, Student>> entries = test2.students.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, Student> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
test2.myTest2();
}
}
list集合存引用数据类型时的问题
集合list的存储元素
(1)如果list中存的是基本数据类型,则存的是值
(2)如果list中存的是引用数据类型(如对象等),则存的是引用
如果对象的引用地址没变,内容变化,也会引起调用该对象时内容变化
下面举一个在集合list中存放对象的例子:
//构建原始数据
ArrayList<Goods> list = new ArrayList();
Goods goods1=new Goods("plum ", 2);
list.add(goods1);
list.add(new Goods("apple", 1));
list.add(new Goods("banana", 2));
//打印原始数据
System.out.println("原始数据:");
for(Goods goods : list){
System.out.println(goods);
}
goods1.setGoodsId(444);//改变goods1的内容
System.out.println("原始数据1:");
for(Goods goods : list){
System.out.println(goods);
}
结果:
原始数据:
Goods{goodsName='plum ', goodsId=2}
Goods{goodsName='apple', goodsId=1}
Goods{goodsName='banana', goodsId=2}
原始数据1:
Goods{goodsName='plum ', goodsId=444}
Goods{goodsName='apple', goodsId=1}
Goods{goodsName='banana', goodsId=2}
结果表明:由于list中存储对象的引用所指的内容发生了变化,所以导致了list中元素内容的改变
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。