Data structure to store 2D-arrays in JAVA - java

i am looking for a data structure to store two dimensional integer arrays.
Is List the rigth data structure or should i use another one?
Can someone give me a short example on how to create such a data structure and how to add a 2d array?
Edit: I want a data structure in which i want to store int[11][7] arrays.
For instance ten, int[11][7] arrays.

If you need to store a number of int[][] arrays in a data structure, I would probably recommend that you store the int[][] arrays in an Object that represents what the data contains, then store these Objects in an ArrayList.
For example, here is a simple Object wrapper for your int[][] arrays
public class 2DArray {
int[][] array;
public 2DArray(int[][] initialArray){
array = initialArray;
}
}
And here is how you would use them, and store them in an ArrayList
// create the list
ArrayList<2DArray> myList = new ArrayList<2DArray>();
// add the 2D arrays to the list
myList.add(new 2DArray(myArray1));
myList.add(new 2DArray(myArray2));
myList.add(new 2DArray(myArray3));
The reason for my suggestion is that your int[][] array must have some meaning to you. By storing this in an Object wrapper class, you can give it a meaning. For example, if the values were co-ordinates, you would call your class Coordinates instead of 2DArray. You, therefore, create a List of Coordinates, which has a lot more meaning than int[][][].

An array is not just an idea about how to store information, it is also an implementation of how to store data. Thus, if you use an array, you have already selected your data structure.
If you want to store data in a data structure, you need to concentrate on how the data structure is used, think about how you will retrieve data and store data, how often you do each operation, and how much data you will be working with. Then you know which methods must be optimum, and have an idea of whether the data can reside in memory, etc.
Just to give you an example of how many ways this could be solved:
You could flatten the array into a 1D array, and use x*num_columns+y as the index
You could create an Object to contain the pair, and put the array in a Map
You could use a linked list containing linked lists.
You could use a tree containing trees.
You could use a list containing trees.
You could create a partial order over the pair and then put all the elements into one tree.
All of these solutions depend heavily on which operations are more important to optimize. Sometime it is more important to update the data structure quickly, sometimes not. The deciding factor is really the rest of your program.

So you want to store a collection of 2D arrays: if the collection is fixed size add another dimension:
int[][][] arrColl
If the collection is variably sized, use your favorite implementation of Collection<int[][]> (ArrayList, LinkedList, etc.):
Collection<int[][]> arrColl

based on your edits :
List<Integer[][]> is what you need - this will allow you to add any numbers of 2D Integer arrays. Note that this will involve boxing and unboxing - something that should be avoided if possible.
If it suffices ( if you know how many 2D int arrays you need in advance ), you can even use int[][][] - a 3D array of ints - this does not involve boxing/unboxing.

If size is fixed, then use int[][] else List<List<Integer>>.

Related

Random Access in Array

I was reading this, advantages of java, where it states that random access is an advantage of arrays in java. I do not understand how can accessing a random element of an array is an advantage. Shouldn't it be a disadvantage?
Why is java allowing to access elements of an array randomly, if the data is stored continuously, shouldn't the data be accessed in an orderly manner?
Random(direct) access implies the ability to access any entry in a array in constant time (independent of its position in the array and of array's size). And that is big advantage.
It is typically contrasted to sequential access. Datastructure has sequential access if we can only visit the values it contains in one particular order.
Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.
Advantage of Java Array
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
Disadvantage of Java Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
It means any element in an array has constant access time O(1). Arrays store it's elements in contiguous memory locations. Arrays store objects with fixed size and any object can be accessed by calculating the offset which is (size*index) instead of traversing the entire array sequentially.
Depends on your use, if you want to access data again, i recommend to see Maps ou HashMaps using , it's the most simple way to work.
If you want to sort an array you can use Arrays.sort(...);

best way to store a list of strings

What would be the best way to store and read a really long string, with each entry is an index for another array?
Right now I have this
String indices="1,4,6,19,22,54,....."
The string has up to hundred of thousand entries, so I think maybe I could use a data structure like Linked List. Does anyone know if it would be faster to use one?
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
you need to declare arraylist of type string.Then add to it.
It would depend on what you'll do with the string (the indices) and the corresponding arrays. Also, it will depend on how you're gonna access them.
I'd suggest you first read an overview about the data structures implemented in java, specially in the Collections Framework.
We could give some suggestions, but you'd have to provide us more information, specially those I mentioned in the beginning (what you want, how this data will be stored and accessed, and so on).
For example, if you need to have a fast access to the indexed data, maybe a string isn't even the best approach. Maybe a map would be better. The indexes could be the keys and the indexed arrays could be the values of the map, for example. But this is just a void example, I strongly suggest you give us more information.
I really like using the ArrayList class, which if your comfortable using arrays, ArrayList or any member of the Collections Framework. Would work really well. For what your trying to do.
ArrayList<String> indices = new ArrayList<String>();
indices.add("");
I have similar hunch in my mind , in which I want to like 1k number of strings and parse them (searching purpose to know it contain item or not).
Hence I found instead of using java collection framework - map or set or list
if I store data simply in array and start parsing data using for-loop, it is faster.
You visit this link and see actual output which we calculated in micro seconds.
https://www.programcreek.com/2014/04/check-if-array-contains-a-value-java/
So using simple brute force is winner in case of unsorted array
(normally we have).
But arrays.BinarySearch() is winner if array is sorted.

How to convert Object[] to Object[][]

Basic Java question:
I have a one dimensional Object, converted from a vector:
Vector<Combination> allValues = getAllValues();
Object[] combinations = allValues.toArray();
Entry combination[n] consists of several integer values like {0,0,0,0}.
I want to create a two dimensional Object 4xN (Object[][]) that i can reach every integer value.
What is the nicest way to create a two dimensional Object from a one dimensional one?
Well, you could of course create an vector of arrays...which is rather ugly. Better thing would be to just keep your 1D Index and compute the indices with offset..
The real question is: What does your data look like; Why do you want 2D indexing?
You need to create an Object[] from each Combination object. Does the combination class have a toArrays() method? If so then you're done. if not then you will have to define one yourself, or if you don't have access to its source, create an Object[] and manually add the values from each combination object.

Java: Change String[][] Dynamically

I have this code:
newArray = new String[][]{{"Me","123"},{"You","321"},{"He","221"}};
And I want to do this dynamically.
Add more elements, things like it.
How do I do this?
PS: Without using Vector, just using String[][];
You can't change the size of an array. You have to create a new array and copy all content from the old array to the new array.
That's why it's much easier to use the java collection classes like ArrayList, HashSet, ...
You can't change the size of arrays. I think you have some options:
use a List<List<String>> to store a list of lists of strings
use a Map<String,String> if you're storing a key/value pair
Vector tends not to be used these days, btw. A Vector is synchronised on each method call, and thus there's a performance hit (negligible nowadays with modern VMs)
Java does not have the facility to resize arrays like some other languages.
But
You would not see a difference between a String array and a ArrayList<String> (javadoc) unless you are specifically required to do so (like in homework)
There are ways where you can declare a enormous array so that you dont run out of space but I would strongly recommend ArrayList for if you need dynamic changes to the size. And ArrayList provides some possibilities that are not (directly) possible with an array, as a bonus.
You can get away with using arrays if it's possible to calculate the size of arrays before using them. In your example, it seems that we need to know the size of the first array only. So you could impose some limit of how many records could be saved, or you could query user to know how many records it needs to save or something similar.
But again, it's easier to use Collections.

Converting to a column oriented array in Java

Although I have Java in the title, this could be for any OO language.
I'd like to know a few new ideas to improve the performance of something I'm trying to do.
I have a method that is constantly receiving an Object[] array. I need to split the Objects in this array through multiple arrays (List or something), so that I have an independent list for each column of all arrays the method receives.
Example:
List<List<Object>> column-oriented = new ArrayList<ArrayList<Object>>();
public void newObject(Object[] obj) {
for(int i = 0; i < obj.length; i++) {
column-oriented.get(i).add(obj[i]);
}
}
Note: For simplicity I've omitted the initialization of objects and stuff.
The code I've shown above is slow of course. I've already tried a few other things, but would like to hear some new ideas.
How would you do this knowing it's very performance sensitive?
EDIT:
I've tested a few things and found that:
Instead of using ArrayList (or any other Collection), I wrapped an Object[] array in another object to store individual columns. If this array reaches its capacity, I create another array with twice de size and copy the contents from one to another using System.copyArray. Surprisingly (at least for me) this is faster that using ArrayList to store the inner columns...
The answer depends on the data and usage profile. How much data do you have in such collections? What is proportions of reads/writes (adding objects array)? This affects what structure for inner list is better and many other possible optimizations.
The fastest way to copy data is avoid copying at all. If you know that obj array is not modified further by the caller code (this is important condition), one of possible tricks is to implement you custom List class to use as inner list. Internally you will store shared List<Object[]>. Each call we just add new array to that list. Custom inner list class will know which column it represents (let it be n) and when it is asked to give item at position m, it will transpose m and n and query internal structure to get internalArray.get(m)[n]. This implementation is unsafe because of limitation on the caller that is easy to forget about but might be faster under some conditions (however, this might be slower under other).
I would try using LinkedList for the inner list, because it should have better performance for insertions. Maybe wrappping Object arra into collection and using addAll might help as well.
ArrayList may be slow, due to copying of arrays (It uses a similar approach as your self-written collection).
As an alternate solution you could try to simply store the Rows at first and create columns when neccessary. This way, copying of the internal arrays at the list is reduced to a minimum.
Example:
//Notice: You can use a LinkedList for rows, as no index based access is used.
List<Object[]> rows =...
List<List<Object>> columns;
public void processColumns() {
columns = new ArrayList<List<Object>>();
for(Object[] aRow : rows){
while (aRow.size() > columns.size()){
//This ensures that the ArrayList is big enough, so no copying is necessary
List<Object> newColumn = new ArrayList<Object>(rows.size())
columns.add(newColumn);
}
for (int i = 0; i < aRow.length; i++){
columns.get(i).add(aRow[i]);
}
}
}
Depending on the number of columns, it's still possible that the outer list is copying arrays internally, but normal tables contains far more rows than columns, so it should be a small array only.
Use a LinkedList for implementing the column lists. It's grows linearly with the data and is O(1). (If you use ArrayList it has to resize the internal array from time to time).
After collecting the values you can convert that linked lists to arrays. If N is the number of rows you will pass from holding 3*N refs for each list (each LInkedList has prevRef/nextRef/itemRef) to only N refs.
It would be nice to have an array for holding the different column lists, but of course, it's not a big improvement and you can do it only if you know the column count in advance.
Hope it helps!
Edit tests and theory indicate that ArrayList is better in amortized cost, it is, the total cost divided by the number of items processed... so don't follow my 'advice' :)

Categories

Resources