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
}
}
同为对象但是内置对象与一般对象又有很多不同!