以下测试主要为了说明:对传递对象或传递引用进行修改,对最终值的影响情况
public class PassTest {
@Before
public void setUp() throws Exception {
}
/**
* 测试对象已经指向具体的值
*/
@Test
public void testPass1() {
// 对象的引用已经指向了具体的对象
Human human = new Someone();
Map<String, String> map = new HashMap<>();
getPerson1(human, map);
System.out.println("human1:" + human + ", map1:" + map.toString());
assertEquals("fish", map.get("food"));
assertEquals("大哥", human.getName());
}
/**
* 测试对象的引用尚未指向了具体的对象
*/
@Test
public void testPass2() {
// 对象的引用尚未指向了具体的对象
Human human = null;
Map<String, String> map = null;
getPerson2(human, map);
System.out.println("human2:" + human + ", map2:" + map);
assertEquals(null, map);
assertEquals(null, human);
}
/**
* 测试对象的引用已经指向了具体的对象,在调用方法中重新指向另一个对象
*/
@Test
public void testPass3() {
// 对象的引用已经指向了具体的对象,在调用方法中重新指向另一个对象
Human human = new Someone();
Map<String, String> map = new HashMap<>();
getPerson3(human, map);
System.out.println("human3:" + human + ", map3:" + map.toString());
assertEquals(0, map.size());
assertEquals(null, human.getName());
}
/**
* 测试对象的引用尚未指向了具体的对象,调用方法中创建对象、赋值,并返回对象的情况
*/
@Test
public void testPass4() {
Human human = null;
human = getPerson4();
System.out.println("human4:" + human);
assertEquals("大哥", human.getName());
}
interface Human {
public String getName();
public void setName(String name);
public void eat(Map<String, String> map);
}
class Someone implements Human {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void eat(Map<String, String> map) {
map.put("food", "fish");
}
@Override
public String toString() {
return "Someone [name=" + name + "]";
}
}
public void getPerson1(Human human, Map<String, String> map) {
human.setName("大哥");
human.eat(map);
}
public void getPerson2(Human human, Map<String, String> map) {
human = new Someone();
map = new HashMap<>();
human.setName("大哥");
human.eat(map);
}
private void getPerson3(Human human3, Map<String, String> map3) {
Human human = new Someone();
Map<String, String> map = new HashMap<>();
human.setName("大哥");
human.eat(map);
human3 = human;
map3 = map;
}
private Human getPerson4() {
Human human = new Someone();
human.setName("大哥");
return human;
}
}
测试结果: