How to create a generic array in Java?

I have to ask a question in return: is your GenSet “checked” or “unchecked”? What does that mean? Checked: strong typing. GenSet knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a Class<E> argument, and methods will throw an exception when they are passed arguments that are not of … Read more

Converting array to list in Java

In your example, it is because you can’t have a List of a primitive type. In other words, List<int> is not possible. You can, however, have a List<Integer> using the Integer class that wraps the int primitive. Convert your array to a List with the Arrays.asList utility method. Integer[] numbers = new Integer[] { 1, … Read more

Converting ‘ArrayList to ‘String[]’ in Java

List<String> list = ..; String[] array = list.toArray(new String[0]); For example: List<String> list = new ArrayList<String>(); //add some stuff list.add(“android”); list.add(“apple”); String[] stringArray = list.toArray(new String[0]); The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, … Read more

How to sort an array of integers correctly

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) – var numArray = [140000, 104, 99]; numArray.sort(function(a, b) { if( a === Infinity ) return 1; else if( isNaN(a)) return -1; else return a – b; }); console.log(numArray); Documentation: Mozilla Array.prototype.sort() … Read more

Get the first element of an array

Original answer, but costly (O(n)): array_shift(array_values($array)); In O(1): array_pop(array_reverse($array)); Other use cases, etc… If modifying (in the sense of resetting array pointers) of $array is not a problem, you might use: reset($array); This should be theoretically more efficient, if a array “copy” is needed: array_shift(array_slice($array, 0, 1)); With PHP 5.4+ (but might cause an index … Read more