简体   繁体   中英

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. For example, if I passed an Integer ArrayList to the method, it would generate 10 random Integers and add them to the ArrayList. If it was a Long ArrayList, it would generate 10 random Long values, and so on.

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". They aren't implicit based on the argument type

Here's what I mean (there's no way to have a generic Random class):

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

}

Pass in a Supplier of the appropriate type:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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