作者kaneson (Lance)
看板java
标题Re: [问题] 参考变数的传递
时间Mon Feb 4 20:48:45 2013
※ 引述《icetofux ()》之铭言:
: 大家好,最近在试着学习java,关於参考变数的运用有点疑问,想向各位先进求教:
: 1 private Node Root;
: 2
: 3 public BTree() {
: 4 Root = null;
: 5 }
: 6
: 7 public void Insert(int TData) {
: 8 Insert( Root, TData);
: 9 return ;
: 10 }
: 11
: 12 private void Insert( Node NowNode, int TData) {
: 13 if(NowNode==null) {
: 14 NowNode = new Node();
: 15 NowNode.Data = TData;
: 16 }
: 17 ...
: 18 return ;
: 19 }
private Node root ;
public BTree() {
root = null ;
}
public void Insert( int data ) {
if ( root == null )
root = new Node( data ) ;
else
Insert( root, data ) ;
}
private void Insert( Node nowNode, int data ) {
if ( data < nowNode.data )
if ( nowNode.left == null )
nowNode.left = new Node( data ) ;
else
Insert( nowNode.left, data ) ;
else if ( data > nowNode.data )
...
return ;
}
Java 的传参考在 C++ 的观念只是传(某address)值,
所以在设计的思考上(Java可能也希望我们统一这样做)
就是要习惯先决定好变数的实体对像,
(例如说建立好新物件实体)再传该变数,
传进去後对应的变数的工作就是处理其内容(例如呼叫界面函式或成员函式).
因此也不太需要再改变参考的对像.
虽然不能像C++的call by reference可以在某些问题上有比较不同或简便的写法,
实际上熟练之後也几乎不会碰到解不了的问题
这也是一种写法的单纯化.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 122.116.4.234