title: Avoid instantiating objects in loops - SONAR complaince
body: <p><strong>Instantiating objects inside loop is the common approach every developer do's.</strong> </p>
  
  <p>We instantiate different objects with different generic and collection types inside loops which is not suggestable. Defining a private method to get instance can solve the issue. But I m looking for the generic approach to attain the same.</p>
  
  <p>Example: In the below code</p>
  
  <pre><code>if (CollectionUtils.isNotEmpty(xList)) {
          for (final X x : xList) {
          final List&lt;Y&gt; yList = new ArrayList&lt;Y&gt;();
          final Z z = new Z();
          populateYList(yList);
          if (CollectionUtils.isNotEmpty(yList)) {
             // do something
          }
      }
  </code></pre>
  
  <p>When we go for generic way, is it object safe? Few of my efforts are below</p>
  
  <pre><code>private &lt;T&gt; List&lt;T&gt; getCollectionIntializer(Class&lt;T&gt; type) {
          return new ArrayList&lt;T&gt;();
      }
  
  
  private &lt;T&gt; T getIntializer(Class&lt;T&gt; clazz) {
          T c = null;
          try {
              c = (T) clazz.newInstance();
          } catch (InstantiationException e) {
              e.printStackTrace();
          } catch (IllegalAccessException e) {
              e.printStackTrace();
          }
          return c;
      }
  </code></pre>
  
  <p>Finally my code looks like</p>
  
  <pre><code>if (CollectionUtils.isNotEmpty(xList)) {
          for (final X x : xList) {
          final List&lt;Y&gt; yList = getCollectionIntializer(Y.class);
          final Z z = getIntializer(Z.class);
          populateYList(yList);
          if (CollectionUtils.isNotEmpty(yList)) {
             // do something
          }
      }
  </code></pre>
  
  <p>Is it a secure way to segregate these methods in separate static class so that it can be used in all the classes. Instantiating objects from out of scope of the class?</p>
  
  <p>Share the thought and thanks in advance</p>