How to handle an object array of Object Arrays - java

I have this code:
Object [] array=new Object array [5];
array[0]= new Object[3];
array[1]=new Object [10];
array[2]=new Object [7];
...
How can I access the 5th element of array[1].
If it was a 2D array I would say:
Object o=array [1][5];
but I don't want 2D array because I don't want to waste memory since the size varies from array to array.
It would be great if someone could answer me this question..
Btw I don't want to use vectors etc...
Thank you

You could do it like this:
//This creates a 5 by ? array
Object[][] array = new Object[5][];
array[0] = new Object[3];
array[1] = new Object[10];
array[2] = new Object[7];
....
edit (thanks to the commenters) :
array is an array of arrays. Each element in array refers to an array of Objects.
The memory is not wasted on having more elements than needed.
It will look like this
[a00][a01][a02]
[a10][a11][a12][a13][a14][a15][a16][a17][a18][a19]
[a20][a21][a22][a23][a24][a25][a12]
If you now would like to access the 6th element of the 2nd array you would do this:
Object myObj = array[1][5];

Related

Change size of an array by an arraylist

One of the main Charucteristic of the Array is immutability(Size of the array cant be changed) but while i was practicing i found myself in this case :
We have an Array with specific size
String[] strArr = new String[1];
And ArrayList with Objects
ArrayList<String> list = new ArrayList<>();
list.add("Alex");
list.add("Ali");
list.add("Alll");
So when we try to convert the list to an array and assign it to strArr , like this
strArr = list.toArray(strArr);
for(String str : strArr ) {
System.out.println(str);
}
It works without a problem even if the size of the array doesnt equal the size of the list
So I JUST WANT TO KNOW HOW THIS IS POSSIBLE , WHEN THE SIZE OF THE ARRAY CANT BE CHANGED ?
New array allocated
strArray first references to a String array of size 1, when you do strArr = list.toArray(strArr);, you change the reference of strArray to a different array. So you are not changing the array size, you are only changing to which array now strArrays refers to.
Possibly you assume that list.toArral(strArr) modifies strArr but that's not the case, as you can read at the java documentation. It reads:
"If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list"
The important section for your case, is where the documentation says: "Otherwise, a new array is allocated", so, no array resize is done.
You can use
strArr = list.subList(0, strArr.length).toArray(strArr);
Basicaly, the List#subList(fromIndex, toIndex) creates a new List with the elements starting in the fromIndex up to toIndex (self-explaintory)
You can read more about in https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-
It changes the reference to a new object. You can check this by calling: System.out.println(strAttr) immediately after you first assign the variable and then again after you call strArr = list.toArray(strArr);

How to append data into a String list in Java

I am new to Java and Here is my code.
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
String[] onedata={"j","k","l"};
the thing I want to do here is that, I want to append the onedata into datas at last index value.
Please help let me know that how can I do this.
You can use an ArrayList because their sizes are mutable. For example:
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
List<String[]> datasList = new ArrayList<>(Arrays.asList(datas));
String[] onedata = {"j","k","l"};
datasList.add(onedata);
datas = datasList.toArray(new String[datasList.size()][]);
The things you are dealing with are arrays (String[]) and multidimensional arrays (String[][]) in Java, not lists. Their length is fixed. Therefore to append a new item to an array in such way that the length increases (so not by replacing the last item in the current array) you would need to create a new array with length n+1, assign the old values to the first n indices and then the new value to the index n+1.

Convert ArrayList<double[][]> to double[][]

I have an array list where each element of it is a double[1][3] list. Now if the array list contains n members, I want my output to be a list of size double[n][3]. Based on this post I tried the following:
ArrayList<double[][]> testArray = new ArrayList<double[][]>();
double [][] testList = new double[testArray.size()][];
for(double [][] temp : testArray){
// temp is a list?
}
I also tried the following:
double [][] test = new double[testArray.size()][3];
test = testArray.toArray(test);
None of them are working for me. Any help would be much appreciated. Thanks.
If all arrays in list have 1st dimension size equal to one then you can try:
ArrayList<double[][]> testArray = new ArrayList<double[][]>();
int testArraySize = testArray.size();
double [][] testList = new double[testArraySize][];
for (int i = 0; i < testArraySize; i++) {
testList[i] = testArray.get(i)[0];
}
I think it's pretty straightforward so I'll comment only on that:
get(i)[0]
This takes i-th element from list, which is a two dimensional array and then [0] operator is invoked which accesses second dimension which is what we want to copy to target array. It all works under requirement that first dimensions of arrays in list have size equal to one.
// temp is a list?
No, it is a two dimensional array - it's a list element.
Your second snippet have no chance of working in that case since toArray creates an array in which every array element is an element from list so three dimensional array would be created. But still if you would use that method then to you would have to provide one dimensional array as a parameter to that method (not two dimensional) because toArray takes and returns one dimensional array. In your case that would be one dimensional array in which every element is a two dimensional array which results in having three dimensional array which is not what you want.
You've got a nice start going on with your for loop. All you need now is to copy content from temp to testList, like this:
List<double[][]> testArray = new ArrayList<double[][]>();
double [][] testList = new double[testArray.size()][];
int pos = 0;
for(double [][] temp : testArray){
testList[pos++] = temp[0];
}
This creates a shallow copy. Any modifications to values of testArray will be "visible" through testList array.
Note on naming: testArray is actually a list, while testList is actually an array.
ArrayList<double[][]>() : means a single dimension array in which each element is a double dimension array.
There are multiple double[][] elements.
If you want a single element, then you can get it with .get(index) method.
If you want to convert ArrayList<double[][]> to double[][][] then slightly change your code as
double[][][] testList = new double[testArray.size()][][];
for(int i=0;i<testArray.size();i++){
testList[i] = testArray.get(i);
}

what is this construction for : Object[]{value1,value2}?

can someone explain to me what
new Object[]{test_name,test_laenge};
means? will it just create a new one dimensional Object with 2 tuple values test_name and test_laenge?
I used this in this construction to extract values from a Database into a resultset and insert those value-tuples into a 2-column JTable...
((DefaultTableModel)table.getModel()).addRow(new Object[]{test_name,test_laenge});
but I dont really understand how this works...
It creates an array of size two, where the entries in the array are test_name and test_laenge
It is the same as:
Object[] array = new Object[2];
array[0] = test_name;
array[1] = test_laenge;
((DefaultTableModel)table.getModel()).addRow(array);
The entries in the array is treated as columns and adds one row in the database.
new Object[]{test_name,test_laenge};
creates a new array (Object[]) with two elements: test_name and test_laenge.
The actual elements are the objects referenced by the two variables.
new Object[]{test_name,test_laenge};
Creates a new array with two elements: test_name and test_laenge.
It is creating an array that holds the type Object and initializing it with two objects.
Explicit declaration of array of object holding two initialized elements of type object.
Object[] ar =new Object[]{element_1,element_2};
Testing ar.length() in this case will return 2 as the size of the initial array.
Note that this is the same as doing:
Object[] arr = new Object[2];
arr[0] = element_1;
arr[1] = element_2

Adding values to already initialized object array in Java?

I'm developing for the Android platform and, to simplify the question, I'm using pseudo-names for the entities.
I have an object array stuff[] of the class StuffClass[].
StuffClass stuff[]={
new StuffClass(Argument, argument, argument),
new StuffClass(argument, argument, argument)
};
I have an activity returning a result of three arguments that I want to then use to add a new object to stuff[]. I've done so as follows:
stuff[stuff.length]=new StuffClass(argument, argument, argument);
and I get ArrayOutOfBounds (Figured that would happen).
So how might I go about creating a new object in the stuff[] array?
Arrays are static you can't change size without creating a new one before. Instead of that you can use a dynamic data structure such as an ArrayList
Example:
List<MyType> objects = new ArrayList<>();
objects.add(new MyType());
Here you forget about array size.
Array in Java is little bit special, it's length is fixed when it's initialized, you can not extend it later on.
What you can do is to create a new array, and use System.arraycopy to generate a new array, here's the sample code:
String[] arr1 = new String[]{"a", "b"};
String[] arr2 = new String[3];
System.arraycopy(arr1, 0, arr2, 0, 2);
arr2[2] = "c";
You cannot increase the size of an existing array. Once it's created, the size of the array is fixed.
You will need to create another bigger array and copy the items from the old array to the new array.
A better alternative is to use an ArrayList. When you add items to an ArrayList, the capacity will grow behind the scenes if needed; you don't have to worry about increasing the size.
you can use the ArrayList to do this
arraylist.add(object);
in java arrays are fixed length. you need to initialise them with the desired length.
Consider using a Collection such as ArrayList which will handle everything for you.
List<StuffClass> myList = new ArrayList<>();
myList.add(...);
Lists support similar behaviour to arrays ie:
myList.set(i, elem);
myArray[i] = elem;
elem = myList.get(i);
elem = myArray[i];
len = myList.size();
len = myArray.length;
You can then convert the list to an array.
StuffClass[] myArray = myList.toArray(new StuffClass[myList.size()]);
If you don't want to use lists consider using System.arrayCopy to create a new array with more elements.
read here for a good description.

Categories