Note that there are some explanatory texts on larger screens.

plurals
  1. POCan you pass an int array to a generic method in java?
    primarykey
    data
    text
    <p>I'm playing around with some code katas and trying to get a better understanding of java generics at the same time. I've got this little method that prints arrays like I like to see them and I have a couple of helper methods which accept an array of 'things' and an index and returns the array of the 'things' above or below the index (it's a binary search algorithm). </p> <p>Two questions, </p> <p>#1 Can i avoid the cast to T in splitBottom and splitTop? It doesn't feel right, or I'm going about this the wrong way (don't tell me to use python or something .. ;) )</p> <p>#2 Do I have to write seperate methods to deal with primitive arrays or is there a better solution?</p> <pre><code>public class Util { public static &lt;T&gt; void print(T[] array) { System.out.print("{"); for (int i = 0; i &lt; array.length; i++) { System.out.print(array[i]); if (i &lt; array.length - 1) { System.out.print(", "); } } System.out.println("}"); } public static &lt;T&gt; T[] splitTop(T[] array, int index) { Object[] result = new Object[array.length - index - 1]; System.arraycopy(array, index + 1, result, 0, result.length); return (T[]) result; } public static &lt;T&gt; T[] splitBottom(T[] array, int index) { Object[] result = new Object[index]; System.arraycopy(array, 0, result, 0, index); return (T[]) result; } public static void main(String[] args) { Integer[] integerArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; print(integerArray); print(splitBottom(integerArray, 3)); print(splitTop(integerArray, 3)); String[] stringArray = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}; print(stringArray); print(splitBottom(stringArray, 3)); print(splitTop(stringArray, 3)); int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // ??? } } </code></pre>
    singulars
    1. This table or related slice is empty.
    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