我从 this 中找到了下面的代码所以问题。到目前为止效果很好,但我遇到了对字符串数组进行洗牌的需要。下面的代码只接受整数数组作为参数。我对 java 还是很陌生,我似乎无法弄清楚如何让该方法在其参数中接受多种数据类型。如果我可以使用相同的方法来随机排列整数数组和字符串数组,那就太好了。谁能帮忙?
static int[] shuffle(int[] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
最佳答案
对于不同的参数,你应该有不同的方法。这将是方法重载。
在你的情况下(对于字符串和整数)
static int[] shuffle(int[] array)
static String[] shuffle(String[] array)
或者您可以在方法的参数中包含对象数组。这样,您必须在调用方法中将 int 数组定义为 Integer 类数组。
static Object[] shuffle(Object[] array)
对象是Java中所有类的父类(super class),子类的对象可以通过父类(super class)的引用来处理。
由于 int 是基本类型,不是类,所以必须将 int 数组定义为 Integer 数组。 Integer 是 int 的类型包装类。
关于java - 如何使方法在 java 中接受不同的参数数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40290585/