java没有c#的ref,那怎么实现引用传递?即,有什么和ref等效的东西吗?
简单的例子:public static void main(String[] args)
{
....
int x = 1, y = 2;
swap(x, y);
System.out.println("x = " + x + ", y = " + y);
....
}//互换两个数
static void swap(int x, int y)
{
x = x + y;
y = x - y;
x = x - y;
} 怎么实现互换x y的值?谢谢指教!
简单的例子:public static void main(String[] args)
{
....
int x = 1, y = 2;
swap(x, y);
System.out.println("x = " + x + ", y = " + y);
....
}//互换两个数
static void swap(int x, int y)
{
x = x + y;
y = x - y;
x = x - y;
} 怎么实现互换x y的值?谢谢指教!
解决方案 »
- 关于java浮点型操作报空置针异常
- 如何实现这个算法?(算法设计与分析 书中的题)
- 哪位仁兄会javafx。请指点一下,
- JTable 中如何实现增加、删除、修改等操作(UP有分)。
- 关于HashTable的问题
- java访问网络的问题
- java调用linux压缩命令
- 光标定位偏移
- 如何用java做连接池,或者配置连接池
- 谁能帮我设置Tomcat?我送100分!
- 请问这里面的proc=con.prepareCall("{call updateage(?,?,?)}");是什么意思呀?为什么还要在双引号里面呢?
- JDT Core patch for Groovy-Eclipse plugin 在哪里下载啊
{
int empty;
empty = x;
x = y;
y = empty;
} 另外定义个参数,实现交换不就得了
不是所有搞java的都知道的
{
int[] a = {1,2,3,4,5};
System.out.println(a[0]);///调用前
swap(a[0]);
System.out.println(a[0]);//调用后
} //互换两个数
static void swap(int i)
{
i++;
}
输出结构都是1
//互换两个数
static void swap(int[] ar)
{
ar[0]++;
}
下面的代码可以了,但是换个数都这么麻烦?有没有简单点的方法? public static void main(String[] args)
{
int x = 1,y = 2;
int[] a = {x,y};
System.out.println(x + " " + y);///调用前
swap(a);
x = a[0];
y = a[1];
System.out.println(x + " " + y);//调用后
} //互换两个数
static void swap(int[] a)
{
int t = a[0];
a[0] = a[1];
a[1] = t;
}
public static void main(String[] args) {
int y = 5;
int x = 9;
y = (x^= (y^= x))^ y ;
System.out.println(x);
System.out.println(y);
}
public static void main(String[] args) {
int[] intArray = {1,2};
test(intArray);
System.out.println(intArray[0]+"-"+intArray[1]);
} public static void test(int[] intArray) {
intArray[0] = intArray[0] + intArray[1];
intArray[1] = intArray[0] - intArray[1];
intArray[0] = intArray[0] - intArray[1];
}
Java实现址传递用的是对象,既然int和Integer都不行那自己封装个不就行了:public class Test15 {
public static void main(String[] args) {
Int x = new Int(1), y = new Int(2);
swap(x, y);
System.out.println("x = " + x + ", y = " + y);
} // 互换两个数
static void swap(Int x, Int y) {
x.value = (y.value ^= (x.value ^= y.value)) ^ x.value;
}
}class Int {
public int value; public Int() {
value = 0;
} public Int(int value) {
this.value = value;
} @Override
public String toString() {
return (Integer.toString(value));
}
}
String 也属于引用传递是吧?
以下代码体现只传递值,怎么可以像数组体现区别来?public class Test3 {
public static void main(String args[]){
String s = "hello";
Test3 t3 = new Test3();
t3.change(s);
System.out.println(s);
}
public void change(String s){
s = "www";
}}