static ArrayList<SomeClass> arr; public static void main(String[] args) { arr = new ArrayList<>(); GenerateNewObjects(new SomeClass, 3); //Вот тут надо создавать новый экземпляр } public static void GenerateNewObjects(SomeClass obj, int count) { for (int i = 0; i < count; i++){ arr.add(i, obj); } } 

SomeClass class abstract

Did so:

 static ArrayList<SomeClass> arr; public static void main(String[] args) { arr = new ArrayList<>(); GenerateNewObjects(new SomeClass1, 3); //SomeClass1 extends SomeClass } public static void GenerateNewObjects(SomeClass obj, int count) { for (int i = 0; i < count; i++){ arr.add(i, obj.getClass().newInstance(), c); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }); } } 

    1 answer 1

    Will fit?

     static ArrayList<SomeClass> arr; public static void main(String[] args) { arr = new ArrayList<>(); GenerateNewObjects(3); } public static void GenerateNewObjects(int count) { for (int i = 0; i < count; i++){ arr.add(i, new SomeClass()); } } 

    UPD. If SomeClass is abstract, and only heirs can be placed in arr , I can offer the following code:

      public static ArrayList<SomeClass> arr; public static void main (String[] args) throws java.lang.Exception { arr = new ArrayList<>(); GenerateNewObjects("test.TestClass", 3); for (SomeClass items : arr) { System.out.println(items); } } public static void GenerateNewObjects(String objClass, int count) throws ClassNotFoundException, IllegalAccessException, InstantiationException { // Если передаваемое имя является наследником SomeClass, то пихаем в лист if (Class.forName(objClass).newInstance() instanceof SomeClass) { //if (SomeClass.class.isInstance(Class.forName(objClass).newInstance())) { for (int i = 0; i < count; i++) { arr.add(i, (SomeClass) Class.forName(objClass).newInstance()); } } } 

    SomeClass can check for SomeClass not even in a method, but before calling it:

     String objClass = "test.TestClass"; if (Class.forName(objClass).newInstance() instanceof SomeClass) { GenerateNewObjects(objClass, 3); } 

    And in the method is not necessarily then


    Addition!

    As @zRrr advises:

    To avoid creating an extra object:

    SomeClass.class.isAssignableFrom( Class.forName( objClass ) ) to check if the class in the string is a subtype of SomeClass

    • Not. SomeClass is an abstract class - others are inherited from it. I forgot to clarify, I apologize - Herrgott
    • It was possible to immediately write) Then it is not clear what you need. Do you want to put someClass descendants in an ArrayList ? - Alexey Shimansky
    • Yes, descendants may be different. More precisely, they will definitely be different - Herrgott
    • @Herrgott made an update ... only a check for SomeClass will have to be done in the method if it suits. If not, we will still think - Alexey Shimansky
    • Class.forName(objClass).newInstance() in! Exactly what you need, thanks! - Herrgott