Assignment of an array - java

I saw this snippet when I was preparing for one of the certification exam on java. Can anybody please explain me how does this work?
public static void main(String args[]) {
String str[] = new String[][] {
{ null },
new String[] { "a", "b", "c" },
{ new String() }
}[0];
System.out.println(str[0]);
}
The o/p is null as expected but I am confused with the assignment of String array 's'.
Is it a single dimension array or two-dimensional?
What does [0] on the righthand side of the assignment mean?
How does new String[] { "a", "b", "c" } work?
Thanks in advance
GPAR

I've split the statement into multiple lines, improving the readability
// First, the array is created, then it is stored into a variable.
// At last, store the result of code below into a String[].
String str[] =
// Create a two-dimensional array
new String[][] {
// Add the first element to the two-dimensional array,
// which is in fact a String[] with one null element in it.
/* element #0 */ new String[] { null },
// Add the second element to the two-dimensional array:
// it's a String[] containing three strings
/* element #1 */ new String[] { "a", "b", "c" },
// Then add the third element to the two-dimensional array,
// which is an empty string.
/* element #2 */ new String[] { new String() }
}
// Then get the first element of our two-dimensional array,
// which returns a String[] with one null element in it.
[0];
So in fact, variable str now contains a String[] with index 0 being null.
At last, str[0] is printed on the screen, which was null.
To answer your questions:
Variable str is a one-dimensional array. The notation String str[] is very ugly and confusing; it should be String[] str. And then you can see more easily that our variable is one-dimensional.
[0] means get the first element of the array (arrays always start with index 0). A certain element of a two-dimensional array is always a one-dimensional array; with other words, a two-dimensional array is an array containing arrays.
So that's why String[] str = new String[][] { ... }[0] is perfectly valid.
new String[] { "a", "b", "c" } creates a string array containing three strings: "a", "b" and "c".
So new String[] { "a", "b", "c" }[2] would return "c".
EDIT
Let me explain it step by step.
Step 1 — This is how we declare a String[] (a String array):
String[] myArray = new String[numberOfElements];
Step 2 — We can also immediately initialize the array with values:
String[] myArray = new String[] {
"some value",
"another value",
"et cetera"
};
Step 2b — We do not need to mention the number of elements, because the compiler already sees that we initialize the array with three elements
String[] myArray = new String[3] {
// ^
"some value", // That number
"another value", // is unnecessary.
"et cetera"
};
Step 3 — Because we declare the array and immediately initialize it, we can omit the new statement:
String[] myArray = {
"some value",
"another value",
"et cetera"
};
Step 4 — Next, we have a two-dimensional array, which is nothing more than an array of arrays.
We can first initialize the one-dimensional arrays and then dump them together in a two-dimensional array, like this:
String[] firstThree = { "a", "b", "c" };
String[] lastThree = { "x", "y", "z" };
String[][] myArray = new String[] {
firstThree,
lastThree
};
Step 5 — But we can also do that at once:
String[][] myArray = new String[] {
new String[] { "a", "b", "c" },
new String[] { "x", "y", "z" }
};
Step 6 — Now we said that we can omit the new statements (see step 3), because the array is initialized immediately after initialization:
String[][] myArray = {
{ "a", "b", "c" },
{ "x", "y", "z" }
};
Step 7 — Right?
Step 8 — Now we have your code:
String str[] = new String[][] {
{ null },
new String[] { "a", "b", "c" },
{ new String() }
}[0];
System.out.println(str[0]);
And let us rewrite your code; effectively it's the same as your piece of code.
// Let us define a new two-dimensional string array, with space for three elements:
String[][] our2dArray = new String[3][];
// Then, let us fill the array with values.
// We will add a String array with exactly one element (that element is `null` by chance)
our2dArray[0] = new String[] { null };
// We define the contents for index 1 of our2dArray
our2dArray[1] = new String[] { "a", "b", "c" };
// At last, the last element:
our2dArray[2] = new String[] { new String() };
// Which is effectively the same as
// new String[] { "" };
We have initialized the array so far.
Step 9 — But then, do you see this snippet?:
}[0];
Step 10 — That means we just grab the first element of our newly created array and store that element to our famous variable named str!
String[] str = our2dArray[0]; // Variable str now contains a
// String array (String[]) with exactly one null-element in it.
// With other words:
// str = String[] {
// 0 => null
// }
Step 11 — Then if we print index 0 of our str array, we get null.
System.out.println(str[0]); // Prints null
Step 12 — You see?

1> str is a one-dimensional array
2> the [0] returns the first element of the array (which in this case is another array)
3> new String[]{"a","b","c"} creates and initialises the string array, so that it contains the 3 specified strings - answers to this question might help you with the various syntax rules for this

This is very ugly code.
this String str[]=new String[][]{{null},new String[]{"a","b","c"},{new String()}}[0]; create and initialize a jagged 2d array of String with some initialization and [0] is there to select the 0th String[] to be assigned to the new str variable (the value will be {null}).
the second line prints some value s[0] which is declared somewhere else.

Related

I am trying to make a JTable populated with data held in a LinkedList of objects

I have the headings and I wanted to loop through a 2d array so it will hold all of the data.
String [] columnNames ={"Name", "Day" , "Month" , "Year"};
Object[][] info = new Object [7][newList.size()-1];
for (int i = 0; i<newList.size(); i++)
{
info[i][0] = { ""+ newList.get(i).getName() };
info[i][1] = { ""+ newList.get(i).getDay() };
}
... and so on.
However, this displays the error:
Array constants can only be used in initializers.
How can I fix this?
I later plan to display this in the following way:
JTable JTable table = new JTable(info, columnNames);
JOptionPane.showMessageDialog(null, new JScrollPane(table),
"List",
JOptionPane.INFORMATION_MESSAGE
);
Here:
info[i][0] = { ""+ newList.get(i).getName() };
Just omit the { }
The point is: info[i][0] is not an array. When using two indexes for a two-dim array, you are already "addressing" a cell in your table.
So, just go for:
info[i][0] = newList.get(i).getName().toString();
(assuming that getName() does not return a string already; in any case "" + is simply not required here, too)
You only use { } when assigning an array in one shot, like
String strs[] = { "first", "second" };
for example!

How can I create a new array by merging specific values

I have created two arrays with values in them.
String[] array1 = {"ab", "bc", "ca"};
String[] array2 = {"zy", "yx", "xz"};
I would like to create a third array that obtains specific values from the two arrays.
{"ab", "ca", "yx"}
Instead of simply merging two arrays, is there a way that I can pluck specific values from other arrays when creating the third array?
In Java
You would need to define an interface by which you decide which item is specific and which is not.
public interface SpecificItemDetect{
boolean isSpecific(String item);
}
Now, you can use this code to create your third array.
List<String> third = new ArrayList<String>();
for (String item : Array1){
if(detector.isSpecific(item)){
third.add(item);
}
}
for (String item : Array2){
if(detector.isSpecific(item)){
third.add(item);
}
}
// Now, you may want to convert the list to array.
String[] thirdArray = new String[third.size()];
third.toArray(thirdArray);
Note: detector in this example is an implementation of a class which implements the interface SpecificItemDetect.
In JavaScript
In JavaScript you would need a function instead of that interface. Something like this:
var filter = function(item){
if(/* item is specific */){
return true;
} else {
return false;
}
}
And create the third array like this:
var third = [];
for (var i = 0, len = Array1.length; i < len; i += 1){
if(filter(Array1[i])){
third.push(item);
}
}
for (var i = 0, len = Array2.length; i < len; i += 1){
if(filter(Array2[i])){
third.push(item);
}
}
You cannot access the memory where the array values are stored. This means, you need to go through the array name. Now, with array name you can refer to a specific value you want to 'pluck'. Do you have any rules for this??
Well, I'm not entirely sure what you mean when you say specific values, but if you mean the values that you showed only then you can do it this way
String[] array1 = {"ab", "bc", "ca"};
String[] array2 = {"zy", "yx", "xz"};
List<String> list1 = new ArrayList<String>();
String[] array3 = new String[list1.size()]; //Skip if you don't need array
list1.add(array1[0]);
list1.add(array1[2]);
list1.add(array2[1]);
list1.toArray(array3); //Skip if you don't need array
Much like what abforce said, but if you simply wanted to know how to use the .add method, that is all you need to do. But if you would like to change the values inside when the "specific values" you need change then the interface will be much better. This code is simiple but not very flexible if you need to change the values in the future.

for-each loops ; String cannot be converted to int?

I need to acess 2D array and write some information there. I want to use for-each loop for this.
Here is my code. But when executing it says ;
q13.java:24: error: incompatible types: String[] cannot be converted to int
wi.write(St[a][b] + "\t");
^
q13.java:24: error: incompatible types: String[] cannot be converted to int
wi.write(St[a][b] + "\t");
What's wrong in my code?
import java.io.*;
class q13{
public static void main(String[] args)
{
String St[][]={ {"STUDENT NO", "STII", "SPD", "PS", "DCCNII", "SEI"},
{"DIT/10/C1/0001", "A", "A-", "B+", "A", "A"},
{"DIT/10/M2/0123", "C-" ,"C" ,"B" ,"B", "B+"},
{"DIT/10/M1/0054", "D" ,"C-" ,"C" ,"B-", "B"},
{"DIT/10/M1/0025", "A" ,"A" ,"A-", "A", "A"},
{"DIT/10/C2/1254", "C" ,"C-" ,"B" ,"B+", "B"} };
try{
BufferedWriter wi = new BufferedWriter(new FileWriter(".\\st_info.txt"));
for(String[] a:St)
{
for(String[] b:St)
{
wi.write(St[a][b] + "\t");
}
wi.write("\r\n");
wi.newLine();
}
wi.close();
}
catch(IOException ex)
{
System.out.print(ex);
}
}
}
It doesn't make sense to use a and b as indexes into an array - they are themselves String[] variables - check the declaration.
If you're trying to iterate over every element in the array, I suspect you want:
for(String[] a : St)
{
for(String b : a)
{
wi.write(b + "\t");
}
wi.write("\r\n");
wi.newLine();
}
(I'd also strongly advise you to follow normal Java naming conversions, and use more meaningful names than "st".)
You are accessing each string, when you call for(String[] a:St). This is the reason you are getting the error you have show. A quick method to solve this is to iterate each element manually in the loop and call the loop index like so:
import java.io.*;
class q13{
public static void main(String[] args)
{
String St[][]={ {"STUDENT NO", "STII", "SPD", "PS", "DCCNII", "SEI"},
{"DIT/10/C1/0001", "A", "A-", "B+", "A", "A"},
{"DIT/10/M2/0123", "C-" ,"C" ,"B" ,"B", "B+"},
{"DIT/10/M1/0054", "D" ,"C-" ,"C" ,"B-", "B"},
{"DIT/10/M1/0025", "A" ,"A" ,"A-", "A", "A"},
{"DIT/10/C2/1254", "C" ,"C-" ,"B" ,"B+", "B"} };
try{
BufferedWriter wi = new BufferedWriter(new FileWriter(".\\st_info.txt"));
int i = 0;
for(String[] a:St)
{
int j = 0;
for(String[] b:St)
{
wi.write(St[i][j] + "\t");
j++;
}
i++;
wi.write("\r\n");
wi.newLine();
}
wi.close();
}
catch(IOException ex)
{
System.out.print(ex);
}
}
}
Note that St (that should be name st to follow Java Naming Conventions) is an array of arrays of Strings.
Let's take a closer look to at your loop:
for(String[] a : St) { // a is an array
for(String[] b : St) { //b is an array (unrelated to a)
wi.write(St[a][b] + "\t"); //error, a and b are arrays
Your first loop should loop on the array of arrays, the inner loop will now loop on the array, which includes Strings:
for(String[] a : St) { // a is an array
for(String b : a) { //b is a String
wi.write(b + "\t");
It seems the answers here have already mentioned the error in your code. However, it only grazes on the cause of your casting error.
In short, you are attempting to call on an index of an array using a String[] and a String as the indices. For example, your code is equivalent to the following...
String[] array = {"My", "first", "array"};
String stringFromArray = array["first"];
You are attempting to call on the index of the array using a String (and String[] in your first for-each loop).
In order to obtain the item in an array you must call it using it's index position (starting with position 0 in java).
The following would be proper use of calling on the specific index...
// index [0] [1] [2]
String[] array = {"My", "first", "array"};
String positionZero = array[0];
String positionOne = array[1];
String positionTwo = array[2];
Your output would be , "My", "first", and "array" respectively.

Expanding an array to pass into varargs

Given this function signature:
public static void test(final String... args) {}
I would like to fit a string and an array of strings into the args:
test("a", new String[]{"b", "c"});
But it is not possible because the second argument is not expanded.
So is it possible to expand an array to fit into varargs?
If that is not possible, what is the shortest way to construct a concatenated string array given one string and a string array? E.g:
String a = "a";
String[] b = new String[]{"b", "c"};
String[] c = // To get: "a", "b", "c"
Thank you.
You can use Guava's ObjectArrays.concat(T, T[]) method:
String a = "a";
String[] b = new String[]{"b", "c"};
String[] c = ObjectArrays.concat(a, b);
Notice the order of arguments. Invoking with (b, a) will also work, but that will append the element to the array rather than prepend (which is what you seem to want). This internally uses System.arraycopy() method.
I don't know any other shorter ways but this is pretty clean to me. With plain java (without ant libraries)
String a = "a";
String[] b = new String[] { "b", "c" };
String[] c = new String[b.length + 1];
c[0]=a;
System.arraycopy(b, 0, c, 1, b.length);
That will work no matter what is the size of b
You could just create a separate array, and put the String "a" first into that array, and then copy the array b[] into the array using System.arraycopy(), and then pass the new array to the method.
You can use StringBuilder:
StringBuilder sb = new StringBuilder();
sb.append(a);
for(String s : b) {
sb.append(s);
}
And then you can convert it back to ArrayList or array of Strings...
Shortest way which comes to my mind (BUT not clean code):
test((a + "," + Arrays.toString(b)).replaceAll("[\\[\\] ]", "").split(","));
Test:
public static void main(String[] args) {
String a = "a";
String[] b = new String[] {"b", "c"};
System.out.println(Arrays.toString(
(a + "," + Arrays.toString(b)).replaceAll("[\\[\\] ]", "").split(",")));
}
Output:
[a, b, c]

Using string in java array

I need to put several strings into a java array for example.
"Dog","Cat","Lion","Giraffe"
"Car","Truck","Boat","RV"
each of the above would be 1 key in the array
array[0] = "Dog","Cat","Lion","Giraffe"
array[1] = "Car","Truck","Boat","RV"
Not sure how to do this,or should I be using something other than an array,and how to get each individual element i.e array[0]"Lion"
Thanks
Declare the array like this:
String [][]array = {
{ "Dog","Cat","Lion","Giraffe"},
{"Car","Truck","Boat","RV"}
};
and use the items like this:
array[0][0]; // this would be "Dog"
array[1][0]; // this would be "Car"
You can use a multidimensional array:
String[][] something =
{
{ "hello", "kitties" },
{ "i", "am", "a", "pony" }
};
Well you can do it by declaring a map like so Map<String, MySweetObject> or create a List<String> and put each list into the array.
You need a jagged array, which is an array of arrays:
String [][]array = { {"Dog","Cat","Lion","Giraffe"}, {"Car","Truck","Boat","RV"}};
You can then access the content as this:
array[0] // will be the String array {"Dog","Cat","Lion","Giraffe"}
array[1] // will be the String array {"Car","Truck","Boat","RV"}
array[0][2] // Lion
array[1][0] // Car

Categories