2012年5月31日23:06:13
對JAVA引用的一點理解
例子不完美,但卻說明問題,一直以來都以為方法的參數是形參,現在終於明白了,有些參數不是形參那麼簡單,是引用,是暗含指針操作的,果然C、C++還是要好好學習滴。。。
import java.util.ArrayList;
import java.util.List;
/**
* Hello world!
*
*/
public class App
{
public static void main(String[] args)
{
Person p = new Person();
p.setAge(30);
p.setName("Lily");
System.out.println(p);
int ar[] =
{ 3, 4, 5 };
for (int i : ar)
{
System.out.print(i + " ");
}
int j = 100;
System.out.println(j);
List<Integer> list = new ArrayList<Integer>();
list.add(123);
list.add(456);
list.add(789);
for (int i : list)
{
System.out.print(i + " ");
}
System.out.println();
System.out.println("----------------------------");
modify(p, ar, j, list);
System.out.println(p);
for (int i : ar)
{
System.out.print(i + " ");
}
System.out.println(j);
for (int i : list)
{
System.out.print(i + " ");
}
System.out.println();
}
private static void modify(Person p, int[] ar, int j, List<Integer> list)
{
p.setAge(50);
p.setName("Mary");
ar[2] = 56;
j = 3;
list.set(1, 321);
list.add(9876);
}
}
public class Person
{
private String name;
private int age;
/**
* @param name
* @param age
*/
public Person(String name, int age)
{
super();
this.name = name;
this.age = age;
}
/**
*
*/
public Person()
{
super();
// TODO Auto-generated constructor stub
}
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 String toString()
{
return "Person [name=" + name + ", age=" + age + "]";
}
}
執行結果:
Person [name=Lily, age=30]
ar --> 3 ar --> 4 ar --> 5 j = 100
list -> 123 list -> 456 list -> 789
----------------------------
Person [name=Mary, age=50]
ar --> 3 ar --> 4 ar --> 56 j = 100
list -> 123 list -> 321 list -> 789 list -> 9876