我是java的新手.如何编写java相当于以下C代码.
void Swap(int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
Run Code Online (Sandbox Code Playgroud)
Eng*_*uad 86
这是一招:
public static int getItself(int itself, int dummy)
{
return itself;
}
public static void main(String[] args)
{
int a = 10;
int b = 20;
a = getItself(b, b = a);
}
Run Code Online (Sandbox Code Playgroud)
Sea*_*oyd 40
简短的回答是:你不能这样做,java没有指针.
但是你可以做类似的事情:
public void swap(AtomicInteger a, AtomicInteger b){
// look mom, no tmp variables needed
a.set(b.getAndSet(a.get()));
}
Run Code Online (Sandbox Code Playgroud)
您可以使用各种容器对象(如集合和数组或具有int属性的自定义对象)执行此操作,但不能使用基元及其包装器(因为它们都是不可变的).但我认为,使用AtomicInteger的唯一方法就是使它成为单行.
顺便说一句:如果您的数据恰好是List,更好的交换方式是使用Collections.swap(List, int, int):
Swaps the elements at the specified positions in the specified list.
(If the specified positions are equal, invoking this method leaves
the list unchanged.)
Parameters:
list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.
Run Code Online (Sandbox Code Playgroud)
显然,真正的目标是对一组int进行排序.这是一个单线Arrays.sort(int[]):
int[] arr = {2,3,1,378,19,25};
Arrays.sort(arr);
Run Code Online (Sandbox Code Playgroud)
检查输出:
System.out.println(Arrays.toString(arr));
// [1, 2, 3, 19, 25, 378]
Run Code Online (Sandbox Code Playgroud)
这里有一个简单的辅助函数来交换一组int中的两个位置:
public static void swap(final int[] arr, final int pos1, final int pos2){
final int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
Run Code Online (Sandbox Code Playgroud)
Pra*_*shi 36
这是使用按位XOR(^)运算符在一行中交换两个变量的方法.
class Swap
{
public static void main (String[] args)
{
int x = 5, y = 10;
x = x ^ y ^ (y = x);
System.out.println("New values of x and y are "+ x + ", " + y);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
x和y的新值是10,5
将此单线程用于任何原始数字类,包括double和float:
a += (b - (b = a));
Run Code Online (Sandbox Code Playgroud)
例如:
double a = 1.41;
double b = 0;
a += (b - (b = a));
System.out.println("a = " + a + ", b = " + b);
Run Code Online (Sandbox Code Playgroud)
输出是 a = 0.0, b = 1.41
Java 中没有指针。但是,每个“包含”对象的变量都是对该对象的引用。要获得输出参数,您必须使用对象。在您的情况下, Integer 对象。
因此,您必须创建一个包含整数的对象,然后更改该整数。你不能使用 Integer 类,因为它是不可变的(即它的值不能改变)。
另一种方法是让该方法返回一个数组或一对整数。
| 归档时间: |
|
| 查看次数: |
163574 次 |
| 最近记录: |