简体   繁体   English

如何使方法在java中接受不同的参数数据类型?

[英]How do I make a method accept different parameter datatypes in java?

I found the code below from this SO question. 我从这个 SO问题中找到了下面的代码。 It has worked great so far, but I have come across the need to shuffle arrays of strings. 它到目前为止工作得很好,但我遇到了改组字符串数组的需要。 The code below only accepts arrays of ints as a parameter. 下面的代码只接受int数组作为参数。 I am still very new to java and I can't seem to figure out how to let the method accept multiple datatypes in it's parameters. 我仍然是java的新手,我似乎无法弄清楚如何让方法接受它的参数中的多个数据类型。 It would be wonderful if I could use the same method to shuffle arrays of ints AND arrays of strings. 如果我可以使用相同的方法来改组整数的数组和字符串数组,那将是非常好的。 Can anyone help? 有人可以帮忙吗?

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;
}

You should have different methods for different parameters. 对于不同的参数,您应该有不同的方法。 This will be method overloading. 这将是方法重载。

In your case (for strings and int) 在你的情况下(对于字符串和int)

static int[] shuffle(int[] array)
static String[] shuffle(String[] array)

Or you can have Object array in argument of your method. 或者您可以在方法的参数中包含Object数组。 That way you have to define your int array as Integer class array in calling method. 这样你就必须在调用方法中将int数组定义为Integer类数组。

static Object[] shuffle(Object[] array)

Object is the superclass of all classes in Java and subclass' object can be handled by superclass' reference. Object是Java中所有类的超类,子类'object可以由超类'引用处理。

Since int is primitive type, not a class, you have to define int array as Integer array. 由于int是基本类型,而不是类,因此必须将int数组定义为Integer数组。 Integer is type wrapper class for int. Integer是int的类型包装类。

You can have two different methods. 您可以使用两种不同的方法。 One that shuffles arrays of ints and one that shuffles arrays of strings. 一个调整int数组和一个shuffles字符串数组。

static String[] shuffleStringArray(String[] ar){
    //method logic goes here
}

The basic structure of your method shouldn't change too much. 你的方法的基本结构不应该改变太多。

Good luck! 祝好运!

Java solves this problem by making arrays covarient. Java通过使数组变形来解决这个问题。 This means that if B is a subtype of A the B[] is a subtype of A[]. 这意味着如果B是A的子类型,则B []是A []的子类型。 This means that you can make you parameter type Object[] and you can pass in any array of object. 这意味着您可以创建参数类型Object[]并且可以传入任何对象数组。 For primitive types like int you still need to write a separate method however because primitives are not objects. 对于像int这样的基本类型,你仍然需要编写一个单独的方法,因为基元不是对象。

Use a generic array this way 以这种方式使用通用数组

static <T> T[] shuffle(T[] 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
      T a = ar[index];
      ar[index] = ar[i];
      ar[i] = a;
    }
    return ar;
}

Invoke it like so: 像这样调用它:

System.out.println(Arrays.toString(shuffle(new Integer[]{1,2,3,4})));

(or) (要么)

System.out.println(Arrays.toString(shuffle(new String[]{"a","b","c"})));

You can't have a method perform the same operations on an int array and a reference type array, because Java treats those as completely different types, and their common superclass ( Object ) lacks functionality as an array. 您不能让方法对int数组和引用类型数组执行相同的操作,因为Java将它们视为完全不同的类型,并且它们的公共超类( Object )缺少作为数组的功能。 However, you seem to be getting at overloading (see Overloading Methods part). 但是,您似乎正在进行重载 (请参阅重载方法部分)。 You can have a seperate implementation of the method for different parameters. 您可以为不同的参数单独实现该方法。 Simply copy/paste your code and replace relevant instances of int with String . 只需复制/粘贴代码并用String替换int相关实例。 This is actually what is done for the primitive type arrays in Arrays.copyOf . 这实际上是对Arrays.copyOf的基本类型数组Arrays.copyOf

You cannot do that if you need to support both objects and primitives. 如果需要同时支持对象和基元,则无法执行此操作。 You need to create an overloaded method for each primitive type and one for Object. 您需要为每个基本类型创建一个重载方法,为Object创建一个重载方法。 Each version of this method will re-implement the same algorithm with diferent data types. 该方法的每个版本将重新实现具有不同数据类型的相同算法。

Your method is analogous to the ones in java.util.Arrays class. 您的方法类似于java.util.Arrays类中的方法。 Take a look at Arrays.java source code from Open JDK. 看看Open JDK中的Arrays.java源代码。

http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/be44bff34df4/src/share/classes/java/util/Arrays.java http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/be44bff34df4/src/share/classes/java/util/Arrays.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM