So why doesn't this work? Not really sure why this isn't possible- I just want to store an array of size 2 inside a 2d array.
I know this would be equivalent to setting storage[0][0] = array[0] and storage[0][1] = array[1], but just wondering why this is incorrect.
public class Test {
public static void main(String[] args) {
boolean[][] storage = new boolean[10][2];
boolean[] array = new boolean[2];
array[0] = true;
array[1] = false;
storage[0][] = array; //Why can't I do this?
}
}
Thanks in advance
You have a stray pair of brackets in your assignment. Just use
storage[0] = array;
First of all boolean[][] storage = new boolean[10][2] declares an array and initialise it.
So, you have created 11 arrays. One of boolean[] element type and 10 of boolean type.
It's good, If you want to access it's members directly, but if you create an inner array lately with new boolean[], it's an overhead.
Use boolean[][] storage = new boolean[10][]; instead.
Then, you can access it's elements, which are boolean[] type, and assign your array to it.
storage[0] = array;
Your problem is the stray square brackets(as I'm sure you know). Your code should look like this:
storage[0] = array;
The previous answers did not really explain why though, so that's what I'll do.
What your trying to do is make the first position(storage[0]) hold the same value as array. array is 1 dimensional, so it can only be part of storage, which is 2 dimensional.
Related
I created a very simple program to create an ArrayList of 2 Dimensional arrays of floats.
But adding new elements in the list seems to overwrite or corrupt previous elements.
What am i doing wrong and how should this functionality be implemented?
import java.util.ArrayList;
public class multiDArrayTest {
public static void main(String[] args) {
float[][] coeff = new float[3][6];
ArrayList<float[][]> basisCoeffs;
basisCoeffs = new ArrayList<float [][]>(2);
coeff[0][0] = 0;
coeff[0][1] = 100;
coeff[0][2] = -50;
basisCoeffs.add(coeff);
coeff[0][0] = 50;
coeff[0][1] = 200;
coeff[0][2] = -400;
basisCoeffs.add(coeff);
System.out.println(basisCoeffs.get(0)[0][0]);
System.out.println(basisCoeffs.get(0)[0][1]);
System.out.println(basisCoeffs.get(0)[0][2]);
//I should get 0 100 -50 50, but i don't? Where does it go ??
System.out.println(basisCoeffs.get(1)[0][0]);
System.out.println(basisCoeffs.get(1)[0][1]);
System.out.println(basisCoeffs.get(1)[0][2]);
}
}
Here you add the array to the ArrayList, you modify that array, then you add it to the ArrayList a second time. So you have two copies of the same array in the ArrayList. I think you are confusing primitives and objects here. Arrays are objects, so they can be modified. When you get the elements out of the ArrayList, you see both elements point to that same array, which you modified, so you get the modified values back out. If you don't want that behavior, just clone the array when you add it to the ArrayList. Something like basicCoeffs.add(coeff.clone());.
What happens is that you have the coeff array with the first values, you add it to the list and everything is fine, but when you edit coeff again before adding it to the list, you also edit the one that is in position 0 of the list, since both coeff as the element in position 0 of the list they refer to the same object in Java. One option would be to create a copy and another to have the two arrays separately. Also, since I observe that your dimensions are static, you can directly add the values to the designated positions, for example:
import java.util.ArrayList;
public class multiDArrayTest {
public static void main(String[] args) {
ArrayList<float[][]> basisCoeffs = new ArrayList<float [][]>(2);
basisCoeffs.add(new float[3][6]);
basisCoeffs.add(new float[3][6]);
// First values of coeffs
basisCoeffs.get(0)[0][0] = 0;
basisCoeffs.get(0)[0][1] = 100;
basisCoeffs.get(0)[0][2] = -50;
// Second values of coeffs
basisCoeffs.get(1)[0][0] = 50;
basisCoeffs.get(1)[0][1] = 200;
basisCoeffs.get(1)[0][2] = -400;
System.out.println(basisCoeffs.get(0)[0][0]);
System.out.println(basisCoeffs.get(0)[0][1]);
System.out.println(basisCoeffs.get(0)[0][2]);
System.out.println(basisCoeffs.get(1)[0][0]);
System.out.println(basisCoeffs.get(1)[0][1]);
System.out.println(basisCoeffs.get(1)[0][2]);
}
}
Arrays in java are Mutable and pass by reference (well, pass by value of reference). this means is you change an element in an array, the reference is changed. So what do we have to do to avoid these side effects?
You can encapsulate Lists and arrays and just add a copy of objects into arrays.
if you're using Java 9 or later you can use List<float[][]> basisCoeffs = List.of(coeff) to add its Item as an immutable list.
you can read more about mutables and immutables here: Immutable class?
I have two identical 2D array's of characters however I want to make it so that when I make changes to one it doesn't effect the other. I am assuming it is because they are sharing the same space in memory and was wondering how to stop this.
private char[][] a;
private char[][] b;
a = new char[8][];
b = new char[8][];
while(file.hasNext()) //reads 8 lines from a file and adds it to text to both arrays
{
char[] constant = file.nextLine().toCharArray();
a[i] = constant;
b[i] = constant;
i++;
}
then if i were to run the code
a[0][0] = 't';
then it also changes b[0][0] to 't'
Arrays are objects. When you assign them like this
int[][] firstArray = getArray(); // Get your array from somewhere
int[][] secondArray = firstArray; // Assign an array
you have only one array, but you have a second variable that references it. Essentially, secondArray[i][j] and firstArray[i][j] refer to the same object in memory by two different names.
To fix this, make a copy of the array. A simple way of doing it is to call the clone() method on the original array, like this:
int[][] secondArray = new int[firstArray.length][];
for (int i = 0 ; i != secondArray.length ; i++) {
secondArray[i] = (int[])firstArray[i].clone();
}
Note: clone() creates a shallow copy. If you
My first idea was:
char[] orig = // something;
char[] copy = orig.clone();
But be aware:
clone() only creates a shallow copy of an array. That means for a 2D-Array with chars you have to clone each subarray.
For further information about clone() click here.
Your code should look something like this
char[][] original = new char[3][3];
char[][] copy = new char[orignal.length][0];
for(int i = 0; i < original.length; i++){
copy[i] = original[i].clone();
}
I have two identical 2D array's of characters however I want to make it so that when I make changes to one it doesn't effect the other. I am assuming it is because they are sharing the same space in memory and was wondering how to stop this.
Arrays don't share memory. Nor do any other variables in Java.
Ergo if changes to one affect the other, you don't have two arrays at all. You only have one, with two references to it. Updating the array via one reference is visible via the other reference.
The solution is therefore to create two arrays, not just one.
I am new in android programming.
Here is my question
I tried to declare an array before onCreate() method like
int[] userselected;
Note that i want to use this array to store ids of buttons user had pressed.
Then i tried to find no. of elements in this array with
int noOfElements = userselected.length;
which game me an error.
Then I changed declaration to
int[] userselected = {};
it worked, but when i tried to put an id in this array with code
userselected[1] = R.id.textview1;
it again gave me an error.
I also tried declaring array as
int[] userselected = new int[4];
but then, when i tried to find how many elements have already been stored,
userselected.length
always gave number 4.
Please tell me, how can i get what i want
You need to use ArrayList. It will give you a more flexible structure giving your case.
ArrayList<Integer> userselected = new ArrayList<Integer>();
userselected.add(R.id.textview1); //To add id.
int noOfElement = userselected.size(); //to get size
an array is fixed size. so when you declare this array
int[] userselected = new int[4]
you are creating an array with a fixed size of 4. The array index is zero based so its from [0] to [3]. I recommend you use an ArrayList object like the top answer states
when you do this:
int[] userselected = {};
it is the same as this:
int[] userselected = new int[0]; // empty
and you got an error from this:
int[] userselected;
because you have not allocated any space in memory
Java primitive arrays, such as int[], are constant in length and cannot contain more than their initial length. If you need an array that can change in size, you need to use fx. a List implementation. I would suggest you read up on basic Java before you start developing Android, it would save you a lot of time in the long run.
I think this page can help: http://www.javaclass.info/classes/java-array/array-examples-demonstration-and-code-snippets.php
In the array declaration you do, you say that its size is 4 elements, therefore the length method will always return 4.
regards
declare it as a integer array then Add this to your code
Integer a=0;
for (int i=0;i>userselected.length;i++)
{
if(userselected[i]!=null)
{
a++;
}
}
then a will give you the count you need:) cheers:)
I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}
I was wondering what the simplest way would be to implement an array who's rank is specified at runtime.
The example I am working on stores a array of boolean values for lattice points, and I want the user to be able to chose how many spatial dimensions the model uses at runtime.
I've looked at the Array.newInstance() method:
dimensionOfSpace = userInputValue; // this value comes from GUI or whatever
int latticeLength = 5; // square lattice for simplicity
int[] dimensions = new int[dimensionOfSpace];
for(int i = 0; i < l.length; i++) l[i] = length;
Object lattice = Array.newInstance(boolean.class, dimensions);
But accessing these values in any sort of way seems to require horribly slow methods such as recursively using Array.get until the returned value is no longer an array, i.e. using isArray().
Am I missing an obvious solution here? I would love to be able to access the values in a way similar to foo[i][j][k].
Looks like what you are looking for is for some way to declare how many dimensions an array has at runtime. I don't know how this could be done using a multidimensional ArrayList, or any multidimensional structure where you have to specify the dimensionality at compile time.
The only answer I see is to use a simple linear array wrapped in a class that converts multidimensional coordinate to and from the its position in the underlying array. This is basically how languages such as C stores multidimensional arrays by using one contiguous chunk of memory.
The code would look something like this:
import java.util.*;
class MultiArray<T>{
private int[] dimensions;
private Object[] array;
public MultiArray(int ... dimensions){
this.dimensions=dimensions;
//Utils.product returns the product of the ints in an array
array=new Object[Utils.product(dimensions)];
}
public void set(T value, int ... coords){
int pos=computePos(coords);
array[pos]=value;
}
public T get(int ... coords){
int pos=computePos(coords);
return (T)(array[pos]);
}
private int computePos(int[] coords){
int pos=0;
int factor=1;
for (int i=0;i<coords.length;i++){
pos+=factor*coords[i];
factor*=dimensions[i];
}
return pos;
}
}
class Main{
public static void main(String args[]){
MultiArray<Integer> m=new MultiArray<Integer>(new int[]{5,4,3});
Random r=new Random();
for(int i=0;i<5;i++)
for(int j=0;j<4;j++)
for(int k=0;k<3;k++)
m.set(r.nextInt(),i,j,k);
for(int i=0;i<5;i++){
for(int j=0;j<4;j++){
for(int k=0;k<3;k++)
System.out.print(m.get(i,j,k)+" ");
System.out.println("");
}
System.out.println("\n");
}
}
}
class Utils{
public static int product(int...a){
int ret=1;
for (int x:a) ret*=x;
return ret;
}
}
Checkout Java Collections. It contains a class called ArrayList that grows in size as needed.
One dimensional
List<Boolean> a = new ArrayList<Boolean>();
Two Dimensional
List<List<Boolean>> b = new List<List<Boolean>>();
Three Dimensional
List<List<List<Boolean>>> c = new List<List<List<Boolean>>>();
And you'd access the item as c.get(i).get(j).get(k) instead of c[i][j][k] as in a 3d array. Or even better, wrap it in your own Class, and use a get() method there. So it becomes:
c.get(i, j, k);
Edit:
To have a multi-dimensional list of depth N, remove the Boolean type indictor and simply create lists as
List level1 = new ArrayList();
List level2 = new ArrayList();
List level3 = new ArrayList();
level1.add(level2);
level2.add(level3);
and so on..
I'm going to use the term 'rank' to mean the 'number-of-dimensions' in your array. So a vector has rank 1, a matrix has rank 2 and so on. You've already accepted an answer that by your own admission is not quite what you want. Here's an alternative to settling for less:
Recall that computer memory is essentially linear and that what a compiler does when it gives you arrays is actually take care of transforming an index expression into a linear address. This is simplest to think about if you assume that all arrays are in contiguous memory, not always true. Suppose that you make a declaration such as ARRAY_OF_TYPE[10][10][10], ie it has 1000 elements. Then the element at position [3][5][4] is (my arrays are indexed from 1 not 0 -- change the sums that follow if you want to) at location baseAddress+354*size_of_element_of_TYPE.
I expect you know where I'm going on this by now ...
At run time your program prompts for a list of integers from the user. Each integer specifies the size of one of the dimensions of the array, the number of integers specifies the rank of the array. Your program does some multiplications and you allocate a vector of the right length. OK, you have to write the indexing and de-indexing functions, but these should be fairly straightforward.
et voila you have an array whose rank is established at run time.
I did a quick google search for "java tensor" which came up with DJEP, could that be something which fits your bill?