Two-dimensional array of different types - java

I want to create a two-dimensional array in which I want to store records from the database. So lets say that the first is of type int and the second of type String (here I am describing just one record so basically types of db columns). How can I do it? Is an array the right data structure for that?

I am not sure I am following, but you might be looking for a Map<Integer,String>. or Map<Integer,List<String>>. [have a look on List, and HashMap]
Map allows association of the key [Integer] to the value [String or List].
Map also allows fast lookup of key, and its attached value.
(*) You should use Map<Integer,List<String>> if you want to attach more then one String per Integer, or alternatively you can use apache commons MultiMap

Arrays can only contain one type. If that type happens to be Object then it can store Object and any of its sub-types, but that doesn't really sound like what you're trying to accomplish here.
It sounds like what you're describing is a 2D array to store database information, with each element in the array being a column in one of the rows. This isn't an array of records, it's an array of column data.
Instead, just store a one-dimensional array of records, where each element of the array is a reference to the entire DB row.

You can do the same thing with the help of this
Object[][] o = new Object[10][10];
o[0][0] = 1;
o[0][1] ="hello";
System.out.println(o[0][0]);
System.out.println(o[0][1]);

You can use
HashMap<Integer, ArrayList<String>>

If you simply want to have one column of String data and another column of int data, this is what you can consider doing:
Declare a 2 dimensional String array
String[][] words = new String[][];
Your first column can contain all the String data. The second column can have the numeric data but in the form of a String. You may want to use the Integer.toString() and Integer.parseInt() methods to do this
words[index][index] = Integer.toString(Integer.parseInt(args));
I'm not sure what exactly you hope to achieve but you may consider modifying this snippet to suit your needs

Related

What is the best way to store a generic List in a Map value?

I am doing a University assignment about developing a Dataframe library (we are supposed to import the data from files such as csv, json and txt). The data structure I chose is HashMap<String, ArrayList<Object>> where the key represents a column label and the value (List) is the column values storage. When the program reads a file the first row goes through a filter which determines which kind of Object it is (Integer, String...) in order to add the data in that way (list.add(new Integer(2)) for example) but I'm not sure if it is the best way to proceed because the program is supposed to make some operations as well such as sort values (comparator), query (predicate)... Take into account every column can contain a different data type.
I also thought about using ArrayList<String> instead and transforming the values when necessary but would not be too optimal and I prefer asking you first.
Thanks a lot in advance.
Example:
LatD LatM LatS NS LonD LonM LonS EW City State
41 5 59 N 80 39 0 W Youngstown OH
Assignment document: https://drive.google.com/file/d/1Saqiw23vQk7Yoh2csmuH2adcktNzDmjP/view?usp=sharing
I'd try using Guava's Multimap instead of constructing Map with List values yourself.
On the other hand I would think about the design. Is the number of columns always the same and you know upfront what values are there? If the answer is yes, how about creating your custom value object with named fields of concrete types? Something like this sample below and implement some Comparators etc if required.
public class ValueRow {
private Integer LatD;
...
private String City;
private String State;
...
}

Problems reading data from a table

Sorry if this is a newbie question.
If I've a table in my database called Settings with mostly columns of type long and I'm returning the last row in the table to a variable called results with this statement:
List results = em.createQuery("SELECT s FROM Settings s ORDER BY s.idsettings DESC").setMaxResults(1).getResultList();
It gives me an array of type Vector with each index holding a Settings array. How do I get access to the data in the Settings array? http://i.imgur.com/G8AxKKU.png
I need to get the column data and store them as longs in my java program so I can work with them.
It gives me an array of type Vector with each index holding a Settings array
No, as shown in your debugger, it returns a Vector that only contains one element (the one you want).
Just retrieve that object and use getters to read its columns.
Settings settings = (Settings)results.get(0);
long batLow = settings.getBatLow();
long batUp = settings.getBatUp();
...

2 Dimentional array with Hash-map

Is there a way to put a 2d array into a Hash map setup?
Example of the array would be two strings {"John", "red"},
{"George", "blue}
And I would want red to correspond to john etc.
I know I can use a nested loop to go through every item in the 2d array but how would then set it up to add them to the hash-map
hashMap.put("John", "red");
Assuming every array has 2 items in the form of {Name, Color}, you can just iterate over it
for(String[] combo : some2DArray){
someHashMap.Put(combo[0], combo[1]); // Or swap them, depending on what you
// want to be the key and the value
}
If you want to avoid the possibility of removing data because you happen to have two people with the same name there are a few approaches you can take:
Keep the old data
Keep the new data
Assign the new data to a new key
Combine the data in the same key
Keep the old data
Perform a check before using HashMap#put and see if the key already exists.
Only add the data if it doesn't exist yet.
Keep the new data
Use the current code, it will overwrite the old value.
Assign the new data to a new key
Create a new key based on your own rules and insert that.
Combine the data in the same key
Define your HashMap as HashMap<String, List<String>> and add the values to the list.
How about implementing a Pair class, so you can use HashMap<Pair<String,String>> ?
EDIT: Might be that I misunderstood your question, is that what yoe were asking?

Apply "formulas" to doubles in an array list of ArrayList?

I have a table that I made by taking array list and storing it into another array list and it is composed of strings and doubles. Now I want to apply formulas to the doubles in the Table and I am wondering how to do this. And is there any way for them to update if the numbers in the table change ?
org.apache.poi.ss.usermodel.FormulaEvaluator has an evaluate() method that may be useful in this context. There's an example here.

String [][] clarification

I'm just asking about this instruction:
String[][] s = new String[2][2];
If i create this variable "s", will i create a string table with 2 lines and 2 columns ?
Or 2 tables with 2 elements?
Thank you for this clarification.
It creates a two-dimensional array with an array of two elements in both dimensions.
Depending on the sole purpose of the variable and the data it actually holds, you're free to interpret the whole whatever way you want. A table (a matrix) with 2 columns and 2 rows is perfectly fine.
Java has no build-in table datatype, the only native basic types of types (metatypes?) are
primitive values (numerics, char and boolean)
arrays (linear indexable collections of variables of the same type).
objects of classes (basically a collection of named variables of specified type, together with some methods, fixed by class). (Strings are examples of this.)
Everything else must be composed of those types. (To complicate this, the array types are all considered subtypes of java.lang.Object, which is the class from which all other classes inherit.)
So you can have arrays of a specific class, classes which have array-types as class variables (fields), and also arrays of arrays, as here.
Your String[][] type consists of arrays of arrays of String, and the new String[2][2] array creation expression creates an array of length two, each element being itself an array of length two. Each element of these arrays can be a string, but on creation it is first null.
s --> [ 0 , 1 ]
| '----> [ null, null ]
|
'---------> [ null, null ]
You now can put in the places of these nulls references to actual String objects, if you want, by using s[0][1] = "Hello"; and similar statements.
As said already by the other answerers, such a 2D-array can be viewed as a table with rows and columns, if you want, but it is nothing special from the language viewpoint.
I think that you are hung up about which is the one true explanation.
In reality, they are are many correct explanations or conceptual models. Which of these is most appropriate / makes the most sense depends on the conceptual level your are thinking at.
At the level of the language / JVM specification you have an array of arrays of strings.
At the syntactic level you have something that looks like a 2-D array of strings, with columns and rows. For a lot of operations it will behave exactly like a 2-D array.
(You can do things to make your String[][] not behave like a conventional 2-D array. For example, you can replace a row to give an "array" in which the rows have different lengths. But that only happens if you "assign" a whole row.)
At the application level what you have can be thought of as a table ... if you want to.
The explanation that you linked to in one of your comments is correct, and so are all of the answers. They are all saying (or trying to say) the same thing.
(BTW - this is what #BalusC's answer is saying. I'm just elaborating.)
So when you ask:
If i create this variable "s", will i create a string table with 2 lines and 2 columns ? Or 2 tables with 2 elements?
... the answer is that it is BOTH of those, depending on your perspective, and how your application uses them. From other perspectives, it is also an array of arrays of strings, or a 2-D array of strings.
You are creating a two dimensional array. This is an array of arrays.
This will technically create an array - of length 2 - of string arrays - also of length 2.
But for all practical purposes it can be thought of as creating a table with 2 rows and 2 columns.
There is no table.
There is an array, an array is simply a reference to the memory where the variables are actually stored.
it will actually create a matrix which is an array of which each element is an array...
array one: [] []
array two: [] []
This is a 2D array. just like writing
String [][] s = new String[2][];
s[0] = new String[2];
s[1] = new String[2];
So I think both your options are correct.

Categories