如何创建可以在多个类作为输入的方法 [英] How to create a method that can take in multiple classes as input

查看:147
本文介绍了如何创建可以在多个类作为输入的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举个例子:

public static String[] multipleOfSameSet(String var,int setLength){
    String[] out = new String[setLength];
    for(int i=0; i<setLength; i++){
        out[i] = var;
    }
    return out;
}

但我想这对于int,double和大约10其他类的工作。
我试图取代字符串使用一个类,它给了我错误的世界。这里:

but I want this to work for int, double and about 10 other classes. I tried using a class in place of String and it gave me a world of errors. Here:

它甚至有可能?如果是的话,我怎么办呢?

Is it even possible?? If yes, how do I do it?

推荐答案

是的,这是可能的。一种选择是,试图找到一类是你要使用的类或接口所有的类都实现的超类。你的情况,唯一的候选人可能是对象:

Yes, it's possible. One option is to try and find a class that is a superclass of all the classes you want to use, or an interface all your classes implement. In your case, the only candidate might be Object:

public static Object[] multipleOfSameSet(Object var, int setLength) {
    Object[] out = new Object[setLength];
    for(int i = 0; i < setLength; i++) {
        out[i] = var;
    }
    return out;
}

这会的工作,因为所有的Java类扩展的对象,无论是直接或间接的。原始值被转换成对象automaticaly(整数成为整数 S,双打成为双击和等等)。

This will work, because all Java classes extend Object, either directly or indirectly. Primitive values get converted into objects automaticaly (ints become Integers, doubles become Doubles and so on).

这种方法的缺点是,嗯,你得到的对象数组回来了,有没有什么你可以用这些做。你可能要考虑,而不是正在你的方法接受一些泛型类型T,并返回T的一个ArrayList

The downside of this approach is that, well, you get an array of Objects back, and there's not much you can do with those. What you might want to consider instead is making your method accept some generic type T, and returning an ArrayList of T's:

public static <T> ArrayList<T> multipleOfSameSet(T object, int setLength) {
    ArrayList<T> out = new ArrayList<T>();
    for(int i = 0; i < setLength; i++) {
        out.add(object);
    }
    return out;
}

不过,如果你不需要事后修改列表,我会去这个:

However, if you don't need to modify the list afterwards, I'd go with this:

public static <T> List<T> multipleOfSameSet(T object, int setLength) {
    return Collections.nCopies(setLength, object);
}

这篇关于如何创建可以在多个类作为输入的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆