简体   繁体   English

根据参数类型向ArrayList添加随机元素?

[英]Add random elements to ArrayList based on argument type?

Sorry if the title is a bit hard to understand. 抱歉,标题有点难以理解。 What I'm trying to do is create a generic method which can take in an ArrayList of any type, and add randomly generated elements to it which are of its type. 我正在尝试做的是创建一个通用方法,该方法可以接收任何类型的ArrayList,并向其添加随机生成的元素(属于该类型)。 For example, if I passed an Integer ArrayList to the method, it would generate 10 random Integers and add them to the ArrayList. 例如,如果我将Integer ArrayList传递给该方法,它将生成10个随机Integer,并将它们添加到ArrayList中。 If it was a Long ArrayList, it would generate 10 random Long values, and so on. 如果它是Long ArrayList,它将生成10个随机Long值,依此类推。

Is there some sort of class or interface which would automatically know which type needs to be generated? 是否有某种类别或接口可以自动知道需要生成哪种类型? The issue with the Random class is that you have to manually call the methods such as "nextInt". Random类的问题在于,您必须手动调用诸如“ nextInt”之类的方法。 They aren't implicit based on the argument type 它们不是基于参数类型隐式的

Here's what I mean (there's no way to have a generic Random class): 这就是我的意思(无法使用通用的Random类):

public static <AnyType> void addRandElements (ArrayList<AnyType> arr){
    arr.add(rand.nextInt());
    return arr;

}

Pass in a Supplier of the appropriate type: 传递适当类型的Supplier

public static <AnyType> void addRandElements (ArrayList<AnyType> arr, Supplier<? extends AnyType> supplier){
  // Surround with a loop to add more than one.
  arr.add(supplier.get());
}

This supplier could return random elements: 该供应商可以返回随机元素:

addRandElements(intList, () -> rand.nextInt());

Or fixed elements: 或固定元素:

addRandElements(strList, () -> "fixed string");

Or elements of some other type: 或其他类型的元素:

addRandElements(listOfLists, ArrayList::new);

But the point is that you need to specify how the elements will be generated, as a parameter to this generic method. 但要点是,您需要指定如何生成元素,作为此通用方法的参数。

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

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