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.
Related
So I want to write a programm, that can manage workouts.I have a class "Excersise" and I will create many Objects from this class. Im wondering how I should handle all these Objects. Till now I had an ArrayList with all Excersises in it but when I want to add an Excersise to a workout, I would have to do it like this: workout.add(excerises.get(index)) meaning I would have to know the index for every excerises. Also Im wondering how good the performany of ArrayLists are. Should I consider to use another data structure?
If you have constant pool of Excersises, and you only need to access them by index, then you can use array instead:
Excersise[] excersises = new Excersise[EXCERSIZE_SIZE];
//fill excersises
//use excersises
workout.add(excersises[index]);
ArrayList is designed to have fast access to element by index, and it is using array underneath, but it has range check inside it's get method. On the other hand ArrayList provide a bunch of useful methods, in case if you need any of them. The other thing is that if you would like to hold a lot of objects in it it might be wise to create it with some capacity, which you expect, knowing of how many objects you will add to this ArrayList, for example if you expect 1000 objects then you can do:
List<Excersise> excersises = new ArrayList(1000);
In that way you'll omit recreating of arrays inside ArrayList.add method when array inside ArrayList will not be able to store provided value (HashMap also has constructor HashMap(int initialCapacity)).
If you would like to access to excersise for example by it's symbolic name, let's say "push ups", then you can use HashMap:
Map<String, Excersise> excersiseByName = new HashMap<>();
//fill excersises
workout.add(excersiseByName.get("push ups"));
I want to create a matrix that contains 5 arrary list.
each array list contains different objects but from the same types (they all Actors but every array list contains a different actor...)
how should I initialize it?
it's basically a game. I want to initialize every actor in the array lists with a position and the general matrix with all the actors/array lists.
create a matrix that contains 5 array lists
ArrayList[] matrix = new ArrayList[5];
each array list contains different objects but from the same types
matrix[0] = new ArrayList<MyCustomClass>();
matrix[0].add(new MyCustomClass(...));
matrix[0].add(new MyCustomClass(...));
how do i get to each actor later
// one way of getting the Actor object if you know
matrix[0].get(index);the index
If you don't know the index, then you will have to traverse the arraylist and find the Actor you want.
Ok, so here's a small problem I'm facing - is there an easy way in Java to cast
ArrayList<Object[]> array;
to
Object[][] data;
?
Object[][] data=array.toArray();
The Object[]'s inside are treated as a type of object themselves. They then are put into their own array, leading to an array of array objects of objects, or simply a two-dimensional array.
Casting is not the solution you are looking for. Casting would essentially allow you to use a method that you cast to a specific class type. An example of a cast:
(((ClassA)classB).method())
So a returned value can be placed inside of a ClassA object from the instantiated classB object that contains method().
What you are wanting to do on the other hand is create a multidimensional array or a 2D array. This is essentially an array of arrays, where arrayA[i] = arrayB[];
For example:
Object[] objectArray = new Object[5];
Object[][] = objectArray2D = new Object[][];
objectArray2D[i] = objectArray;
Here is a point to your question though, if you create a multidimensional array, why would you feed it only one array instance. Essentially what you would create in the above example is an array inside of an array, and since you will be giving it only 1 array indexing of all the objects inside the array would be the same as if you had the one array, but with one additional placement. Let me explain:
objectArray[0] == the object you placed on the first slot of objectArray
while objectArray2D[0][0] == the exact same object as the object in objectArray[0]
You are not receiving any advantage by using a multidimensional array for one array. If you were to ask the 2D array for the index [1][0] you would receive an out of bounds exception.
Lastly, I would suggest that you create a specific form of array, such as int[], or string[]. The problem with a Object[] array is that you can store anything that is considered an Object into the array, allowing for a potential cluster of different types of Objects inside one array. Example you could have a objectArray[0] = int 1; and objectArray[1] = String one; Unless you want to be very specific in the array use, it might be better to use one Object type as the array.
In any case the final solution to do exactly what you are wanting to do is as follows:
ArrayList<Object[]> array;
Object[][] data;
public void changeToAnArray(ArrayList<Object[]> array, Object[][] data)
{
this.array = array.toArray();
this.data[0] = array;
}
Also due note the point of an ArrayList, is to have a 2D array in essence without having to parse the indexes.
Please anyone feel free to correct on the parts I am wrong on << still learning.
I'm trying to figure out the best and most efficient way for this scenario with a map. It needs to be an array. I've made a dummy example to explain this.
Basically if there is a map that consists of some sandwhich id and and sandwhich details and I only want the ones with lettuce to be in an array.
The problem with arrays is that the size must be known, in this case I do not know how many sandwhiches with lettuces there will be. I could use an array list but I would need to convert it to an array - some copy method which would make this inefficient.
Example:
//Assume that this map is given
Map<Integer, Sandwich> sandwiches = //some method gets all sandwiches
Meal[] meal = new Meal[sandwiches.size()];
for(Map.Entry<Integer, Sandwich> e : sandwiches.entrySet())
{
if(e.getValue().hasLettuce())
meal = new Meal(e.getValue);
}
//mandatory: An array must be returned
return meal;
Use an ArrayList. There's no way to avoid making copies if you don't know how many Meals you'll need, the amortized cost of the copies is cheap, and lists are a better conceptual fit for the problem than arrays anyway. You can call list.toArray(new Meal[0]) to get an array if you really want one.
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>>.