Note that there are some explanatory texts on larger screens.

plurals
  1. POJava how to: Generic array creation from class with generic?
    primarykey
    data
    text
    <p>I have a class <code>FirstClass&lt;O&gt;</code> and a class <code>SecondClass&lt;O&gt;</code>, and I want to make an O[] in <code>SecondClass&lt;O&gt;</code> inside a routine which is called from <code>FirstClass&lt;O&gt;</code>, where O is a generic class parameter. I fail to find how to do this.</p> <p>I need an O[] specifically (and not <code>ArrayList&lt;O&gt;</code> or similar) because I need to get elements from it very often inside the body of a loop, and it matters for the execution time of my algorithm.</p> <p>So I would want something along these lines.</p> <pre><code>public class FirstClass&lt;O&gt; { void someRoutine(n and other params) { //Do some stuff SecondClass&lt;O&gt; = new SecondClass(n, possibly_other_params); //Do some stuff } } </code></pre> <p>and</p> <pre><code>public class SecondClass&lt;O&gt; { O[] myArray; SecondClass&lt;O&gt;(int n, possibly_other_params) { //Here the constructor that creates an O[n] } } </code></pre> <p>Some methods I found on the web, but do not work for my case:</p> <ul> <li>Use <code>O[] array = (O[]) new Object[n];</code> but that doesn't compile.</li> <li>Use <code>Object[] array = new Object[n];</code> and do an (O) cast every time I request something from the array, but this is way too slow</li> <li>Use <code>Array.newInstance(Class&lt;O&gt; type, int n);</code>, with <code>O o;</code> and <code>type=o.class</code> but it complains that <code>type</code> is now of type <code>Class&lt;CAP#1&gt;</code> instead of type <code>Class&lt;O&gt;</code>, whatever CAP#1 means...</li> </ul> <p>How should I do this properly in Java, with optimal execution speed in mind?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload