I have this code is to find the indexOf 3 elements in array, so I used java.util.. etc, but it gives me that there I mistake the result is -1, how to avoid this wrong answer, and is there another way to write this code
int array [] = {1,0,1,0,0,1,1,0,1,1};
for(int counter = 0 ; counter < 3; counter++)
System.out.printf("%5d%8d\n",java.util.Arrays.asList(array).
indexOf(array[randomNumbers.nextInt(10)]),array[randomNumbers.nextInt(10)]);
I'm not sure if I've got the answer, but try breaking up your code into readable lines. And your original array should be Integer[] instead of int[].
Note that Arrays.asList(int[]) creates a List<int[]>.
Random randomNumbers = new Random();
Integer array [] = {1,0,1,0,0,1,1,0,1,1};
for(int counter = 0 ; counter < 3; counter++)
{
int randomItemFromArray = array[randomNumbers.nextInt(10)];
List<Integer> listOfInts = Arrays.asList(array);
int indexOfRandomItem = listOfInts.indexOf(randomItemFromArray);
System.out.printf("%5d%8d\n", indexOfRandomItem , randomItemFromArray);
}
This might help.
You have to use wrapper class of "int"
SecureRandom randomNumbers = new SecureRandom();
Integer array[] = { 1, 0, 1, 0, 0, 1, 1, 0, 1, 1 };
for (int counter = 0; counter < 3; counter++)
System.out.printf("%5d%8d\n", java.util.Arrays.asList(array).indexOf(array[randomNumbers.nextInt(10)]), array[randomNumbers.nextInt(10)]);
(Edit - 02.03.2014)
Hi, my first answer was wrong, check the new one:
SecureRandom randomNumbers = new SecureRandom();
/**
* I don't know why but when you create an array with only primitive
* contained "unnamed block" like "Integer array[] = {1,0,1}". JVM
* associate same referance variables with same values like "Integer
* array[] = {#34, #554, #34}". That is why i use "new Integer"
* constractor for each integer as follows:
*/
Integer array[] = new Integer[] { new Integer(1), new Integer(0),
new Integer(1), new Integer(0), new Integer(0), new Integer(1),
new Integer(1), new Integer(0), new Integer(1), new Integer(1) };
int ran, i;
for (int counter = 0; counter < 3; counter++) {
ran = randomNumbers.nextInt(10);
i = 0;
/**
* "List.indexOf" method uses "object1.equals(object2)" method, this
* method compares "values" of wrapper classes, but in your case
* we have to compare referances, so with nested "for" loops we
* check that:
*/
for (Integer integer : array) {
if (integer == array[ran]) { // "==" operator checks referances is same
System.out.printf("%5d%8d\n", i, ran);
break;
}
i++;
}
}
Problem is with the int[] array itself because when you use any primitive array and convert it to a List using Arrays.asList() it will return a List<int[]> not List<Integer> hence the issue occurring with your code. to resolve create array of Integer (Wrapper class)
Integer[] array = {1,0,1,0,0,1,1,0,1,1};
Why your code fails:
This is relevant:
Arrays.asList() not working as it should?
You call Arrays.asList on an int[]. This does not produce the expected result because Arrays.asList is made to work with an array of Objects, not primitives. The result is a list of one element, that element is your int[] array (because an array of primitives is an Object, like any other array).
The solutions:
You already know your index. You're setting it. No need to look it up. Save it in a variable. I love short code, but sometimes short code is worse and runs slower than slightly longer code. NBD if you didn't fit the entire program on one line. -OR-
If you still think you need an index lookup, use an array of integer objects (Integer[]).
Related
Suppose we have the Java code:
Object arr = Array.newInstance(Array.class, 5);
Would that run? As a further note, what if we were to try something like this:
Object arr1 = Array.newInstance(Array.class, 2);
Object arr2 = Array.newInstance(String.class, 4);
Object arr3 = Array.newInstance(String.class, 4);
Array.set(arr1, 0, arr2);
Array.set(arr1, 1, arr3);
Would arr1 then be a 2D array equivalent to:
String[2][4] arr1;
How about this: what if we don't know the dimensions of this array until runtime?
Edit: if this helps (I'm sure it would...) we're trying to parse an array of unknown dimensions from a String of the form
[value1, value2, ...]
or
[ [value11, value12, ...] [value21, value22, ...] ...]
And so on
Edit2: In case someone as stupid as I am tries this junk, here's a version that at least compiles and runs. Whether or not the logic is sound is another question entirely...
Object arr1 = Array.newInstance(Object.class, x);
Object arr11 = Array.newInstance(Object.class, y);
Object arr12 = Array.newInstance(Object.class, y);
...
Object arr1x = Array.newInstance(Object.class, y);
Array.set(arr1, 0, arr11);
Array.set(arr1, 1, arr12);
...
Array.set(arr1, x-1, arr1x);
And so on. It just has to be a giant nested array of Objects
It is actually possible to do in java. (I'm a bit surprised I must say.)
Disclaimer; I never ever want to see this code anywhere else than as an answer to this question. I strongly encourage you to use Lists.
import java.lang.reflect.Array;
import java.util.*;
public class Test {
public static int[] tail(int[] arr) {
return Arrays.copyOfRange(arr, 1, arr.length);
}
public static void setValue(Object array, String value, int... indecies) {
if (indecies.length == 1)
((String[]) array)[indecies[0]] = value;
else
setValue(Array.get(array, indecies[0]), value, tail(indecies));
}
public static void fillWithSomeValues(Object array, String v, int... sizes) {
for (int i = 0; i < sizes[0]; i++)
if (sizes.length == 1)
((String[]) array)[i] = v + i;
else
fillWithSomeValues(Array.get(array, i), v + i, tail(sizes));
}
public static void main(String[] args) {
// Randomly choose number of dimensions (1, 2 or 3) at runtime.
Random r = new Random();
int dims = 1 + r.nextInt(3);
// Randomly choose array lengths (1, 2 or 3) at runtime.
int[] sizes = new int[dims];
for (int i = 0; i < sizes.length; i++)
sizes[i] = 1 + r.nextInt(3);
// Create array
System.out.println("Creating array with dimensions / sizes: " +
Arrays.toString(sizes).replaceAll(", ", "]["));
Object multiDimArray = Array.newInstance(String.class, sizes);
// Fill with some
fillWithSomeValues(multiDimArray, "pos ", sizes);
System.out.println(Arrays.deepToString((Object[]) multiDimArray));
}
}
Example Output:
Creating array with dimensions / sizes: [2][3][2]
[[[pos 000, pos 001], [pos 010, pos 011], [pos 020, pos 021]],
[[pos 100, pos 101], [pos 110, pos 111], [pos 120, pos 121]]]
Arrays are type-safe in java - that applies to simple arrays and "multi-dimensional" arrays - i.e. arrays of arrays.
If the depth of nesting is variable at runtime, then the best you can do is to use an array that corresponds to the known minimum nesting depth (presumably 1.) The elements in this array with then either be simple elements, or if further nesting is required, another array. An Object[] array will allow you to do this, since nested arrays themselves are also considered Objects, and so fit within the type system.
If the nesting is completely regular, then you can preempt this regularity and create an appropriate multimensional array, using Array.newInstance(String.class, dimension1, dimension2, ...), If nesting is irregular, you will be better off using nested lists, which allow for a "jagged" structure and dynamic sizing. You can have a jagged structure, at the expence of generics. Generics cannot be used if the structure is jagged since some elements may be simple items while other elements may be further nested lists.
So you can pass multiple dimensions to Array.newInstance, but that forces a fixed length for each dimension. If that's OK, you can use this:
// We already know from scanning the input that we need a 2 x 4 array.
// Obviously this array would be created some other way. Probably through
// a List.toArray operation.
final int[] dimensions = new int[2];
dimensions[0] = 2;
dimensions[1] = 4;
// Create the array, giving the dimensions as the second input.
Object array = Array.newInstance(String.class, dimensions);
// At this point, array is a String[2][4].
// It looks like this, when the first dimension is output:
// [[Ljava.lang.String;#3e25a5, [Ljava.lang.String;#19821f]
//
// The second dimensions look like this:
// [null, null, null, null]
The other option would be to build them up from the bottom, using getClass on the previous level of array as the input for the next level. The following code runs and produces a jagged array as defined by the nodes:
import java.lang.reflect.Array;
public class DynamicArrayTest
{
private static class Node
{
public java.util.List<Node> children = new java.util.LinkedList<Node>();
public int length = 0;
}
public static void main(String[] args)
{
Node node1 = new Node();
node1.length = 1;
Node node2 = new Node();
node2.length = 2;
Node node3 = new Node();
node3.length = 3;
Node node4 = new Node();
node4.children.add(node1);
node4.children.add(node2);
Node node5 = new Node();
node5.children.add(node3);
Node node6 = new Node();
node6.children.add(node4);
node6.children.add(node5);
Object array = createArray(String.class, node6);
outputArray(array); System.out.println();
}
private static Object createArray(Class<?> type, Node root)
{
if (root.length != 0)
{
return Array.newInstance(type, root.length);
}
else
{
java.util.List<Object> children = new java.util.ArrayList<Object>(root.children.size());
for(Node child : root.children)
{
children.add(createArray(type, child));
}
Object array = Array.newInstance(children.get(0).getClass(), children.size());
for(int i = 0; i < Array.getLength(array); ++i)
{
Array.set(array, i, children.get(i));
}
return array;
}
}
private static void outputArray(Object array)
{
System.out.print("[ ");
for(int i = 0; i < Array.getLength(array); ++i)
{
Object element = Array.get(array, i);
if (element != null && element.getClass().isArray())
outputArray(element);
else
System.out.print(element);
System.out.print(", ");
}
System.out.print("]");
}
}
As a further note, what if we were to try something like this:
Object arr1 = Array.newInstance(Array.class, 2);
Object arr2 = Array.newInstance(String.class, 4);
Object arr3 = Array.newInstance(String.class, 4);
Array.set(arr1, 0, arr2);
...
No, you can't set an String[] value like that. You run into
Exception in thread "main" java.lang.IllegalArgumentException: array element type mismatch
at java.lang.reflect.Array.set(Native Method)
at Test.main(Test.java:12)
Ok, if you are unsure of the dimensions of the array, then the following method won't work. However, if you do know the dimensions, do not use reflection. Do the following:
You can dynamically build 2d arrays much easier than that.
int x = //some value
int y = //some other value
String[][] arr = new String[x][y];
This will 'dynamically' create an x by y 2d array.
So I came across this question with code to extract coefficients from a polynomial with variable numbers of variables. So a user might
want the coefficient array for a polynomial in two variables 3 x^2 + 2 x y or it could be one with three variables. Ideally, you want a multiple dimension array which the user can easily interrogate so can be cast to
Integer[], Integer[][] etc.
This basically uses the same technique as jdmichal's answer, using the Array.newInstance(obj.getClass(), size) method. For a multi dimensional arrays obj can be an array of one less dimension.
Sample code with randomly created elements
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Random;
public class MultiDimArray {
static Random rand = new Random();
/**
* Create an multi-dimensional array
* #param depth number of dimensions
* #return
*/
static Object buildArray(int depth) {
if(depth ==1) { // For 1D case just use a normal array
int size = rand.nextInt(3)+1;
Integer[] res = new Integer[size];
for(int i=0;i<size;++i) {
res[i] = new Integer(i);
}
return res;
}
// 2 or more dimensions, using recursion
int size = rand.nextInt(3)+1;
// Need to get first items so can find its class
Object ele0 = buildArray(depth-1);
// create array of correct type
Object res = Array.newInstance(ele0.getClass(), size);
Array.set(res, 0, ele0);
for(int i=1;i<size;++i) {
Array.set(res, i, buildArray(depth-1));
}
return res;
}
public static void main(String[] args) {
Integer[] oneD = (Integer[]) buildArray(1);
System.out.println(Arrays.deepToString(oneD));
Integer[][] twoD = (Integer[][]) buildArray(2);
System.out.println(Arrays.deepToString(twoD));
Integer[][][] threeD = (Integer[][][]) buildArray(3);
System.out.println(Arrays.deepToString(threeD));
}
}
Effective Java item # (I don't remember ) : Know and use the libraries.
You can use a List and use the toArray method:
List<String[]> twoDimension = new ArrayList<String[]>();
To convert it to an array you would use:
String [][] theArray = twoDimension.toArray( new String[twoDimension.size()][] );
The trick is, the outer array is declared to hold String[] ( string arrays ) which in turn can be dynamically created with another List<String> or, if your're parsing strings with the String.split method.
Demo
Focusing on the dynamic creation of the array and not in the parsing, here's an example on how does it works used in conjunction with String.split
// and array which contains N elements of M size
String input = "[[1],[2,3],[4,5,6,7],[8,9,10,11,12,13]]";
// Declare your dynamic array
List<String[]> multiDimArray = new ArrayList<String[]>();
// split where ],[ is found, just ignore the leading [[ and the trailing ]]
String [] parts = input.replaceAll("\\[\\[|\\]\\]","")
.split("\\],\\[");
// now split by comma and add it to the list
for( String s : parts ){
multiDimArray.add( s.split(",") ) ;
}
String [][] result = multiDimArray.toArray( new String[multiDimArray.size()][]);
There. Now your result is a two dimensional dynamically created array containing : [[1], [2, 3], [4, 5, 6, 7], [8, 9, 10, 11, 12, 13]] as expected.
Here's a complete running demo, which also adds more regexp to the mix, to eliminate white spaces.
I let you handle the other scenarios.
I have a programming assignment where I am tasked with the following:
I am taking two int values (x and y) and creating two different arrays: the first (size x) will print an array starting from x and descending down to 1. The second (size y) will take random values from the first array (size x) and store it in its own array. I will then print out the second array. However, the second array cannot have any repeating values. For example, if the array was size 10, it could not have two of the same digit within its 10 individual indexes. I am attempting to store unique elements in my second array by creating two arrays, one boolean to check for unique elements and another one to store those unique elements. Here is my code:
/*
* user will enter desired size x for first array labeled arr_1
* arr_1 will contain values descending from x down to 1
* user will enter desired size y for second array labeled arr_2
* arr_2 will contain random values taken from arr_1 w/o repeating numbers
*/
import java.util.Arrays;
// import java.util.Arrays;
import java.util.Random;
// import java.util.Scanner;
public class Prog1B
{
public static void main(String[] args)
{
System.out.println("Program 1B, Christopher Moussa, masc1574");
// Scanner scnr = new Scanner(System.in);
int x = 20;
int v = x;
int[] arr_1 = new int[x];
for (int i = x-1; i >= 0; i--)
{
arr_1[i] = v; // System.out.print(i+1 + " "); prints 20, 19, ... , 1
v--; // System.out.print(arr_1[i] + " "); prints 20, 19, ... , 1
}
// int[] b = unique(arr_1);
System.out.println(Arrays.toString(unique(arr_1)));
}
public static int[] unique (int[] n)
{
boolean[] seen = new boolean[n.length];
int[] unique = new int[n.length];
Random rand = new Random(123L);
for (int i = 0; i < n.length; i++)
{
int index = rand.nextInt(n.length);
while (seen[index])
{
index = rand.nextInt(n.length);
}
unique[i] = n[index];
}
return unique;
}
}
The code compiles and runs, but it still prints out an array with repeating values. I am trying to write the program so that it does not print out an array with repeating values, only unique values. Do you have any suggestions as to where the problem lies? I am pretty sure it lies within the "unique" method, more specifically when the boolean array is checking for unique values (I noticed while trying to debug that even if the random index it generated was not unique, it still skipped the while condition and printed it out). I am a beginning programmer (a freshman at San Diego State studying computer science) and any feedback/advice will be greatly appreciated. Thanks you very much.
I found the problem in your code. You never update your "seen" Boolean array. See the code below for fix:
public static int[] unique (int[] n){
boolean[] seen = new boolean[n.length];
int[] unique = new int[n.length];
Random rand = new Random(123L);
for (int i = 0; i < n.length; i++)
{
int index = rand.nextInt(n.length);
while (seen[index])
{
index = rand.nextInt(n.length);
}
seen[index] = true; //boolean array updated
unique[i] = n[index];
}
return unique;
}
Using this fix, I was able to get the output below (which has no repeats):
[3, 11, 17, 10, 16, 18, 15, 6, 14, 20, 7, 13, 1, 19, 9, 2, 5, 4, 12, 8]
You need to even set your array seen[index] = true;
public static int[] unique (int[] n)
{
boolean[] seen = new boolean[n.length];
int[] unique = new int[n.length];
Random rand = new Random(123L);
for (int i = 0; i < n.length; i++)
{
int index = rand.nextInt(n.length);
while (seen[index])
{
index = rand.nextInt(n.length);
}
unique[i] = n[index];
seen[index] = true;
}
return unique;
}
Unless you specifically have to do it this way, I suggest you take a step back and try a totally different approach, something like this:
Set<int> mySet = new HashSet<int>(Arrays.asList(someArray));
NOTE: You will want to adjust the return type of unique() to be Set
The rest of the implementation is left as an excercise for the reader. Basically you take the array and convert it to a set as the example above.
(Credit where credit is due)
I just wanted to steer you in the right direction per https://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions
Good luck, I would say the biggest lesson here is how to walk away from code that has become inefficient when a better solution exists. Good luck!
Heres is how to do this using java8 lambdas
ArrayList<Integer> arrayli = new ArrayList<Integer>(Arrays.asList(arr_1));//converted array to list
System.out.println();
List<Integer> distinctIntegers = arrayli.stream().
.distinct()
.boxed()
.collect(Collectors.toList());
distinctIntegers.foreach(System.out::println);
I am creating a class that will play the role of a computer player in a virtual game of sticks. However, when I use the constructor method for this class, I lose the array that I have created, even though I had already declared the array in the state attributes. After 20 minutes, I am completely lost.
I am new to Java, and am trying to learn and get better. Any help would really be appreciated.
Below is the redesigned AI class along with the error that Eclipse keeps on submitting.
public class RedesignedAI {
private int[][] largeArray;
private int AIChoiceStick;
private Random random = new Random();
private int CurrentScore[] = new int[51]; //at max, if 100 sticks are initially chosen, then each player takes at max 50 sticks,
private int h = 0; //^so why not have one more in case
public RedesignedAI(int NumberSticks) //this is a constructor method and creates the arrays that contains a
{
largeArray[][] = new int[NumberSticks][3];
int i = 0;
while(i < NumberSticks)
{
largeArray[i][0] = 1; //ADD THIS
largeArray[i][1] = 1;
largeArray[i][2] = 1;
i++;
}
}
The error: largeArray cannot be resolved to a type.
You initialized the largeArraythe wrong way. Use:
largeArray = new int[NumberSticks][3];
That new allocate a 2D array, so types are coherent both sides of the =.
If you want to allocate chunk by chunk then you should use [] syntax:
largeArray = new int[NumberSticks][]; // array of NumberSticks entries to array of int (not yet determined)
for (int i=0; i<NumberSticks; i++) {
largeArray[i] = new int[3]; // i-th entry of array largeArray is a new array of 3 ints
}
largeArray is a reference to array of reference to array of ints. largeArray[i] is a reference to array of ints. largeArray[i][j]is an int.
Try this
private int[][] largeArray = null;
Initially initialize with null.
then in constructor
largeArray[][] = new int[3][3];
Since value is dynamic and you are changing it anyhow
You have to initialize the array on the top:
private int[][] largeArray = new int[x][y];
An array always has a fixed length. Only a list can variate the length.
Change this:
largeArray[][] = new int[NumberSticks][3];
into this:
largeArray = new int[NumberSticks][3];
Wrong Code:
largeArray[][] = new int[NumberSticks][3];
Instead use:
largeArray = new int[NumberSticks][3];
You don't need the [][] in the largeArray code of the constructor. This will do:
largeArray = new int[NumberSticks][3];
You may find it easier to use ArrayList instead. Maybe something like this:
private List<List<Integer>> largeArray;
...
public RedesignedAI(int NumberSticks) {
largeArray = new ArrayList<>();
int i = 0;
while(i < NumberSticks) {
List<Integer> innerArray = new ArrayList<>();
innerArray.add(1);
innerArray.add(1);
innerArray.add(1);
largeArray.add(innerArray);
i++;
}
}
I am trying to make a method in which it will take an array of integers as a parameter, creates a new array that is the same size, copies the elements from the first array into the new array, and then returns a reference to the new array.
Right now, my code is as follows:
class CopyingAnArray {
int[] cloneArray(int[] arr) {
size = newarray.length;
int[] newarray = new int[size];
int[] copyarray = newarray;
return copyarray;
}
public static void main(String argv[]) {
ArrayTester converter = new ArrayTester();
int[] newarray = {2,5,6,7};
System.out.println(converter.cloneArray(newarray));
}
}
Here is an explanation of what I think I am doing. I am taking the size of an array and putting it an array:
size = newarray.length;
int[] newarray = new int[size];
Then I am copying the array into a new array named copyarray. Then, I return copyarray.
int[] newarray = new int[size];
int[] copyarray = newarray;
return copyarray;
Any suggestions or advice on what I did wrong/solve the code?
so I tried doing this instead:
So, I will do something like this:
int[] cloneArray(int[] arr) {
int size=arr.length;
int[] arr=new int[size];
int[] arr=newarray;
for (int i=0; i<arr.length; i++) {
arr[i]=newarray[i];
return newarray[i];
}
}
I am still getting errors though.
Multiple things. You need to declare size as an int. The major things: you never use the parameter passed to the method, arr. You use size = newarray.length when newarray doesn't exist yet. You try to make copyarray = new array, which doesn't make much sense. In addition, when setting two arrays equal to each other, you aren't really copying, you are only copying the reference to the array in memory. In order to copy, make a new array with the length of the parameter, then iterate over it with a for loop and copy each value into the new array, then return the new array. You can also always use Arrays.copyOf(array,array.length);
Suppose we have the Java code:
Object arr = Array.newInstance(Array.class, 5);
Would that run? As a further note, what if we were to try something like this:
Object arr1 = Array.newInstance(Array.class, 2);
Object arr2 = Array.newInstance(String.class, 4);
Object arr3 = Array.newInstance(String.class, 4);
Array.set(arr1, 0, arr2);
Array.set(arr1, 1, arr3);
Would arr1 then be a 2D array equivalent to:
String[2][4] arr1;
How about this: what if we don't know the dimensions of this array until runtime?
Edit: if this helps (I'm sure it would...) we're trying to parse an array of unknown dimensions from a String of the form
[value1, value2, ...]
or
[ [value11, value12, ...] [value21, value22, ...] ...]
And so on
Edit2: In case someone as stupid as I am tries this junk, here's a version that at least compiles and runs. Whether or not the logic is sound is another question entirely...
Object arr1 = Array.newInstance(Object.class, x);
Object arr11 = Array.newInstance(Object.class, y);
Object arr12 = Array.newInstance(Object.class, y);
...
Object arr1x = Array.newInstance(Object.class, y);
Array.set(arr1, 0, arr11);
Array.set(arr1, 1, arr12);
...
Array.set(arr1, x-1, arr1x);
And so on. It just has to be a giant nested array of Objects
It is actually possible to do in java. (I'm a bit surprised I must say.)
Disclaimer; I never ever want to see this code anywhere else than as an answer to this question. I strongly encourage you to use Lists.
import java.lang.reflect.Array;
import java.util.*;
public class Test {
public static int[] tail(int[] arr) {
return Arrays.copyOfRange(arr, 1, arr.length);
}
public static void setValue(Object array, String value, int... indecies) {
if (indecies.length == 1)
((String[]) array)[indecies[0]] = value;
else
setValue(Array.get(array, indecies[0]), value, tail(indecies));
}
public static void fillWithSomeValues(Object array, String v, int... sizes) {
for (int i = 0; i < sizes[0]; i++)
if (sizes.length == 1)
((String[]) array)[i] = v + i;
else
fillWithSomeValues(Array.get(array, i), v + i, tail(sizes));
}
public static void main(String[] args) {
// Randomly choose number of dimensions (1, 2 or 3) at runtime.
Random r = new Random();
int dims = 1 + r.nextInt(3);
// Randomly choose array lengths (1, 2 or 3) at runtime.
int[] sizes = new int[dims];
for (int i = 0; i < sizes.length; i++)
sizes[i] = 1 + r.nextInt(3);
// Create array
System.out.println("Creating array with dimensions / sizes: " +
Arrays.toString(sizes).replaceAll(", ", "]["));
Object multiDimArray = Array.newInstance(String.class, sizes);
// Fill with some
fillWithSomeValues(multiDimArray, "pos ", sizes);
System.out.println(Arrays.deepToString((Object[]) multiDimArray));
}
}
Example Output:
Creating array with dimensions / sizes: [2][3][2]
[[[pos 000, pos 001], [pos 010, pos 011], [pos 020, pos 021]],
[[pos 100, pos 101], [pos 110, pos 111], [pos 120, pos 121]]]
Arrays are type-safe in java - that applies to simple arrays and "multi-dimensional" arrays - i.e. arrays of arrays.
If the depth of nesting is variable at runtime, then the best you can do is to use an array that corresponds to the known minimum nesting depth (presumably 1.) The elements in this array with then either be simple elements, or if further nesting is required, another array. An Object[] array will allow you to do this, since nested arrays themselves are also considered Objects, and so fit within the type system.
If the nesting is completely regular, then you can preempt this regularity and create an appropriate multimensional array, using Array.newInstance(String.class, dimension1, dimension2, ...), If nesting is irregular, you will be better off using nested lists, which allow for a "jagged" structure and dynamic sizing. You can have a jagged structure, at the expence of generics. Generics cannot be used if the structure is jagged since some elements may be simple items while other elements may be further nested lists.
So you can pass multiple dimensions to Array.newInstance, but that forces a fixed length for each dimension. If that's OK, you can use this:
// We already know from scanning the input that we need a 2 x 4 array.
// Obviously this array would be created some other way. Probably through
// a List.toArray operation.
final int[] dimensions = new int[2];
dimensions[0] = 2;
dimensions[1] = 4;
// Create the array, giving the dimensions as the second input.
Object array = Array.newInstance(String.class, dimensions);
// At this point, array is a String[2][4].
// It looks like this, when the first dimension is output:
// [[Ljava.lang.String;#3e25a5, [Ljava.lang.String;#19821f]
//
// The second dimensions look like this:
// [null, null, null, null]
The other option would be to build them up from the bottom, using getClass on the previous level of array as the input for the next level. The following code runs and produces a jagged array as defined by the nodes:
import java.lang.reflect.Array;
public class DynamicArrayTest
{
private static class Node
{
public java.util.List<Node> children = new java.util.LinkedList<Node>();
public int length = 0;
}
public static void main(String[] args)
{
Node node1 = new Node();
node1.length = 1;
Node node2 = new Node();
node2.length = 2;
Node node3 = new Node();
node3.length = 3;
Node node4 = new Node();
node4.children.add(node1);
node4.children.add(node2);
Node node5 = new Node();
node5.children.add(node3);
Node node6 = new Node();
node6.children.add(node4);
node6.children.add(node5);
Object array = createArray(String.class, node6);
outputArray(array); System.out.println();
}
private static Object createArray(Class<?> type, Node root)
{
if (root.length != 0)
{
return Array.newInstance(type, root.length);
}
else
{
java.util.List<Object> children = new java.util.ArrayList<Object>(root.children.size());
for(Node child : root.children)
{
children.add(createArray(type, child));
}
Object array = Array.newInstance(children.get(0).getClass(), children.size());
for(int i = 0; i < Array.getLength(array); ++i)
{
Array.set(array, i, children.get(i));
}
return array;
}
}
private static void outputArray(Object array)
{
System.out.print("[ ");
for(int i = 0; i < Array.getLength(array); ++i)
{
Object element = Array.get(array, i);
if (element != null && element.getClass().isArray())
outputArray(element);
else
System.out.print(element);
System.out.print(", ");
}
System.out.print("]");
}
}
As a further note, what if we were to try something like this:
Object arr1 = Array.newInstance(Array.class, 2);
Object arr2 = Array.newInstance(String.class, 4);
Object arr3 = Array.newInstance(String.class, 4);
Array.set(arr1, 0, arr2);
...
No, you can't set an String[] value like that. You run into
Exception in thread "main" java.lang.IllegalArgumentException: array element type mismatch
at java.lang.reflect.Array.set(Native Method)
at Test.main(Test.java:12)
Ok, if you are unsure of the dimensions of the array, then the following method won't work. However, if you do know the dimensions, do not use reflection. Do the following:
You can dynamically build 2d arrays much easier than that.
int x = //some value
int y = //some other value
String[][] arr = new String[x][y];
This will 'dynamically' create an x by y 2d array.
So I came across this question with code to extract coefficients from a polynomial with variable numbers of variables. So a user might
want the coefficient array for a polynomial in two variables 3 x^2 + 2 x y or it could be one with three variables. Ideally, you want a multiple dimension array which the user can easily interrogate so can be cast to
Integer[], Integer[][] etc.
This basically uses the same technique as jdmichal's answer, using the Array.newInstance(obj.getClass(), size) method. For a multi dimensional arrays obj can be an array of one less dimension.
Sample code with randomly created elements
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Random;
public class MultiDimArray {
static Random rand = new Random();
/**
* Create an multi-dimensional array
* #param depth number of dimensions
* #return
*/
static Object buildArray(int depth) {
if(depth ==1) { // For 1D case just use a normal array
int size = rand.nextInt(3)+1;
Integer[] res = new Integer[size];
for(int i=0;i<size;++i) {
res[i] = new Integer(i);
}
return res;
}
// 2 or more dimensions, using recursion
int size = rand.nextInt(3)+1;
// Need to get first items so can find its class
Object ele0 = buildArray(depth-1);
// create array of correct type
Object res = Array.newInstance(ele0.getClass(), size);
Array.set(res, 0, ele0);
for(int i=1;i<size;++i) {
Array.set(res, i, buildArray(depth-1));
}
return res;
}
public static void main(String[] args) {
Integer[] oneD = (Integer[]) buildArray(1);
System.out.println(Arrays.deepToString(oneD));
Integer[][] twoD = (Integer[][]) buildArray(2);
System.out.println(Arrays.deepToString(twoD));
Integer[][][] threeD = (Integer[][][]) buildArray(3);
System.out.println(Arrays.deepToString(threeD));
}
}
Effective Java item # (I don't remember ) : Know and use the libraries.
You can use a List and use the toArray method:
List<String[]> twoDimension = new ArrayList<String[]>();
To convert it to an array you would use:
String [][] theArray = twoDimension.toArray( new String[twoDimension.size()][] );
The trick is, the outer array is declared to hold String[] ( string arrays ) which in turn can be dynamically created with another List<String> or, if your're parsing strings with the String.split method.
Demo
Focusing on the dynamic creation of the array and not in the parsing, here's an example on how does it works used in conjunction with String.split
// and array which contains N elements of M size
String input = "[[1],[2,3],[4,5,6,7],[8,9,10,11,12,13]]";
// Declare your dynamic array
List<String[]> multiDimArray = new ArrayList<String[]>();
// split where ],[ is found, just ignore the leading [[ and the trailing ]]
String [] parts = input.replaceAll("\\[\\[|\\]\\]","")
.split("\\],\\[");
// now split by comma and add it to the list
for( String s : parts ){
multiDimArray.add( s.split(",") ) ;
}
String [][] result = multiDimArray.toArray( new String[multiDimArray.size()][]);
There. Now your result is a two dimensional dynamically created array containing : [[1], [2, 3], [4, 5, 6, 7], [8, 9, 10, 11, 12, 13]] as expected.
Here's a complete running demo, which also adds more regexp to the mix, to eliminate white spaces.
I let you handle the other scenarios.