参数传递2

java的设计者对底层的java实现代码做了太多封装,和C语言中的传递方式相比,复杂很多,而且还有很多种不同情况,让我们看一看:
大家先看看下面这一种情况:就是如果map中存放的是String,Integer等java内置对象时候,它里面存放的并不是真正的对象引用;但是当存放的是一般对象时,存放的就是类似于C语言中的引用,这时我们修改对象的同时也反映到Map中的,这相当于C语言中的真正的引用传递,传递的是对象的地址;但是内置对象就不同:
  package test;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Person {
 static final Log log = LogFactory.getLog(test.class);
public Person(String name, int age) {
  super();
  this.name = name;
  this.age = age;
 }
String name;
int age;
public String getName() {
 return name;
}
public void setName(String name) {
 this.name = name;
}
public int getAge() {
 return age;
}
public void setAge(int age) {
 this.age = age;
}
@Override
public int hashCode() {
 final int prime = 31;
 int result = 1;
 result = prime * result + age;
 result = prime * result + ((name == null) ? 0 :name.hashCode());
 return result;
}
@Override
public boolean equals(Object obj) {
 if (this == obj)
  return true;
 if (obj == null)
  return false;
 if (getClass() != obj.getClass())
  return false;
 Person other = (Person) obj;
 if (age != other.age)
  return false;
 if (name == null) {
  if (other.name != null)
   return false;
 } else if (!name.equals(other.name))
  return false;
 return true;
}
public static void  main(String [] args){
 Person p=new Person("afei",22);
 Person p1=new Person("afei1",22);
 Map hashmap=new HashMap();
 Set hashset=new HashSet();
 hashmap.put("person1",p);
 hashmap.put("person2",p1);
 hashset.add(p);
 hashset.add(p1);
 log.info(hashset.size());
 p.age=90;
 Integer count=3;
 hashmap.put("count",count);
 count=new Integer(count.intValue()+100);
 log.info(((Person)hashmap.get("person1")).getAge());//输出90,值已经改变
 log.info(((Integer)hashmap.get("count")));//依然输出3
 
}
}
同为对象但是内置对象与一般对象又有很多不同!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值