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.
Related
I need to solve two problems for our project, where (1) I have to find a way in which I can keep an array (String[] or int[]) as a key of the Map. The requirement is that, if the contents of two arrays are equal (String[] a={"A","B"}, String[] b={"B","A"}) then they should be considered as equal/same keys, i.e., if I use a, or b as key of Map then a.equal(b)=true
I found that Java Sets adds the hashcodes of all the objects stored in them. The addition of hashcode allows to compare two hashsets, to see if they are equal or not, this means that such mechanism allows to compare two java Sets based on their contents.
So for the above problem I can use Sets as a Key of the Map, but the thing is I want to use Arrays as Key. So any idea for this?
(2) the next thing is, we are interested in an efficient partial key matching mechanism. For instance, to see if any key in the Map contains a portion of the Array, such as to find some thing like Key.contains(new String[]{"A"}).
Please share your ideas, any alternate way of doing this, I am concern with space and time optimal implementations. As this will be used in Data Stream processing projects. So space and time is really an issue.
Q1 - You can't use bare arrays as HashMap keys if you want key equality based on the array elements. Arrays inherit equals(Object) and hashCode() implementations from java.lang.Object, and they are based on object identity, not array contents.
The best alternative I can think of is to wrap the arrays as (immutable) lists.
Q2 - I don't think there is a simple efficient way to do this. The best I can think of are:
Extract all possible subarrays of each array and make each one an alternative key in the hash table. The problem is that the keys will take O(N M^2) space where M is the average (?) number of strings in the primary key String[]'s . Lookup will still be O(1).
Build an inverted index that gives the location of each string in all of the keys, then do a "phrase search" for a sequence of strings in the key space. That should scale better in terms of space usage, but lookup is a lot more expensive. And it is complicated.
I try to use lambda expression in Java8 to solve your problem
For Problem 1:
String[] arr1 = {"A","B","A","C","D"};
List<String> list1 = new ArrayList<String>(new LinkedHashSet<>(Arrays.asList(arr1)));
list1.stream().forEach(x -> System.out.println(x));
If you would like to compare them if they are equal. I suggest you could sort them first and then compare.
Of course, It's much better to use Set and Hashcode to do comparsion
For Problem 2(Some variable in the above would be re-used):
String[] arr2 = {"A"};
List<String> list2 = new ArrayList<String>(Arrays.asList(arr2)); //Assume List2 element is also unique
int NumOfKeyContain = list1.stream().filter(a -> (list2.stream().filter(b -> !b.equals(a)).count())<list2.size())
.collect(Collectors.toList())
.size();
System.out.println(NumOfKeyContain); //NumOfKeyContain is the number that of key in list2 contained by list1
How do I determine which column in a double ArrayList has the same value in all rows? My ArrayList looks like the image below.
Update: Seems like there are many where were confused by the question. I should have asked in a more eloquent way.
I have a two dimensional ArrayList which consists of ArrayLists. I have a certain number of rows and columns in this two dimensional ArrayList. I would like to create a method that would return how many numbers of columns are in that ArrayList. That was what I meant in my original question. Now I know how to create this method as I got help from some of the answers below.
I suppose you have an ArrayList of ArrayLists, then you can do this to retrieve number of "columns":
list.get(0).size()
It means get the first ArrayList from list and get it's size.
Assuming that you just have nested ArrayLists, and the number of rows is represented by the "top" ArrayList size, you can just get the size of the first nested one:
aList.get(0).size();
...assuming of course that aList is your top most ArrayList.
Do you mean you have a
List<List<MyType>> listOfList = ...
and you want to know the size of the inner dimension?
int width = listOfList.get(0).size();
assuming all lists/rows are the same size/width.
I would like to proof whether there is a Float.POSITIVE_INFINITY in my j-th column and row. But I do not know how I can do this, by not having an exploding time complexity. This means I do not want to use for loops for doing this. But I haven't found any alternative way.
Do you know one?
My second thing is I want to copy some columns and/or rows from my 2d array in Java. For rows I can simply use Array[i] to copy it. But for columns I cannot use such form of code. But is there a possibility to do it without for loops?
Basically you have the following options.
Wrap the array into a sepearate class. Use getters and setters where you can check the values when they are assigned and do, whatever you need to do with it.
Loop over the array once it is filled.
After all, there is no way around it that you have to loop if you don't use the first approach. If you have a signal when the array is finished you only have to do it once, but for a more precise approach it would be helpfull to see the code how you fill the array and how you are using the array.
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
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.