Java数组操作与命令行参数使用详解
1. 数组返回与传递
在Java中,当我们需要返回数组时,为了避免调用者修改原始数组,对于基本类型数组可以使用 clone() 方法。示例代码如下:
public int[] getMagicNumbers () {
/* Never do the following. If you do this, callers of this
method will be able to change the magic numbers.
*/
// return this.magicNumbers;
/* Do the following instead. In case of reference arrays, make a deep copy, and
return that copy. For primitive arrays you can use the clone() method.
*/
return (int[]) magicNumbers.clone();
}
同时,我们可以直接创建数组并将其传递给方法,而无需将数组引用存储在变量中。例如,有一个 setNumbers(int[] nums) 方法:
setNumbers(new int[]{10, 20, 30});
需要注意的是,必须使用 new
超级会员免费看
订阅专栏 解锁全文
64

被折叠的 条评论
为什么被折叠?



