Hello only have a few hours with Java. (from Python)
I am trying to define a multidimensional array and populate it with the "add" method. however, I am seeing some bizarre results:
List<String[]> DrawInstructions = new ArrayList<String[]>();
String[] pair = {"",""};
pair[0]="UW";
pair[1]="100";
DrawInstructions.add(pair);
pair[0]="UM";
pair[1]="10";
DrawInstructions.add(pair);
pair[0]="UT";
pair[1]="50";
DrawInstructions.add(pair)
I expected DrawInstructions to end up with this:
[("UW,"100"),("UM","10"),("UT","50")]
But instead I am getting:
[("UT","50"),("UT","50"),("UT","50")]
I am sure this is pretty elemental but I cant figure it out, I have searched for a couple of hours. Thank you for any advice.
Problem is, you're changing the same array over and over — .add() does not create a copy for you. Try the following:
List<String[]> DrawInstructions = null;
String[] pair = {"",""};
pair[0]="UW";
pair[1]="100";
DrawInstructions.add(pair);
pair = new String[] {"",""};
pair[0]="UM";
pair[1]="10";
DrawInstructions.add(pair);
pair = new String[] {"",""};
pair[0]="UT";
pair[1]="50";
DrawInstructions.add(pair);
or, better then,
List<String[]> drawInstructions = new ArrayList<String[]>();
drawInstructions.add(new String[] {"UW", "100"});
drawInstructions.add(new String[] {"UM", "10"});
drawInstructions.add(new String[] {"UT", "50"});
which would be closer to Java naming standards, avoid NPEs, minimize local state, and be arguably more readable.
You are adding the same array (pair) three times. All you do is changing it's value(content).
Remember that java operates on references, not on the copies of the objects.
Try to create pair1, pair2, pair3.
You defined only one String[] pair = {"",""};
You edited the same object 3 times and added that to the list.
You could do that:
List<String[]> DrawInstructions = new ArrayList<String[]>();
String[] pair1 = {"",""};
pair1[0]="UW";
pair1[1]="100";
DrawInstructions.add(pair1);
String[] pair2 = {"",""};
pair2[0]="UW";
pair2[1]="100";
DrawInstructions.add(pair2);
....
Related
Let's say I have in Java 8 the following objects defined:
String[] filledArr = new String[] {"Hallo"};
String[] moreFilledArr = new String[] {"Hallo", "duda"};
String[] emptyArr = new String[] {};
Now I want to create an array containing these two string arrays. How do I write this?
I tried:
String[][] = {emptyArr, filledArr, moreFilledArr};
This doesn't work. Then I tried:
(String[])[] = {emptyArr, filledArr, moreFilledArr};
With the brackets in the second version I want to indicate that the array is one of string arrays and not a two-dimensional array. Still no success.
What's the correct way to do it? Is there one? Or do I have to resort to ImmutableList to create an immutable data-structure here.
You have forgotten to give the variable a name? Both of these work.
String[][] array = {emptyArr, filledArr, moreFilledArr};
String[][] array = new String[][] {emptyArr, filledArr, moreFilledArr};
I recommend you to go through the basic Java syntax specification and tutorials. Start with The Java Tutorials by Oracle Corp, free of cost.
these two are right too
String[][] array = {emptyArr, filledArr, moreFilledArr};
String[][] array = new String[][] {emptyArr, filledArr, moreFilledArr};
please do check these too
Docs for Array in Java Have a Look for more clarification
tutorial of array with java docs
,
I had to add this as a comment but I couldn't, I want to extend with more resources mentioned above , Thanks
We can also achieve it by initialising and assigning to a single dimensional array of type Object. Something like below.
String[] filledArr = new String[] {"Hallo"};
String[] moreFilledArr = new String[] {"Hallo", "duda"};
String[] emptyArr = new String[] {};
Object[] newArr = {filledArr, moreFilledArr, emptyArr};
If you want to print the values inside this newArr, then you shall use the below code.
for (int i=0;i< newArr.length; i++){
Arrays.stream(((String[]) newArr[i])).forEach(System.out::println);
}
How do you add a String[] into a String[] in Java? To be more clear, my desired output is:
String[][] out = {{"A", "AA"},{"B", "BB"}};
I don't know the size of the output array, it can contain more then two elements. Basically, I wanted to do it like this (don't mind the syntax it's a blend of Python):
String [] out;
String[] temp = {"A","AA"};
out.append(temp)
So now out should look like {{"A","AA"}}. Then I can append {"B", "BB"} creating the desire output above? This is what my thought was, but I'm not sure if it can be done. I am more experienced with Python and it can be done in Python, but I am wanting to do this in Java. Any ideas?
As in the comment mentioned, you can use the List to store all the array values inside.
It is when you put in:
List<String[]> list = new ArrayList<>();
String[] array = {"A", "B"};
list.add(array);
...
And it is when you get out:
String[] array = list.get(0 /*i*/);
Try using List for this purpose as you would have more operations to perform on Lists than an Array.
List<List<String>> out = new ArrayList<>();
List<String> temp = new ArrayList<String>();
temp.add("A");
temp.add("AA");
out.add(temp);
Read through the Javadocs for more on this.
You can either use List or ArrayList that dynamically grows.
ArrayList al = new ArrayList();
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
For differences between List and ArrayList Type List vs type ArrayList in Java
Detailed Methods of ArrayList
You could try this way too if you exactly want to add dynamic array of Strings into another dynamic array.
List<List<String>> addresses = new ArrayList<List<String>>();
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
addresses.add(singleAddress);
Because in Java, Array is a fixed length data structure so you should try java List which supports dynamically insertion and deletion of elements. An example using java.util.ArrayList is following:
java.util.List<String[]> out = new java.util.ArrayList<String[]>();
String[] temp = {"A","AA"};
out.add(temp);//insertion
And using index (started from 0), we can get element like out.get(0); and can remove element like out.remove(0);
Suppose I have a lot of String Variables(100 for example):
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
....
String str100 = "zzz";
I want to add these String variables to ArrayList, what I am doing now is
ArrayList<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
...
list.add(str100);
I am curious, is there a way to use a loop? For example.
for(int i = 1; i <= 100; i++){
list.add(str+i)//something like this?
}
Use an array:
String[] strs = { "abc","123","zzz" };
for(int i = 0; i < strs.length; i++){
list.add(strs[i]); //something like this?
}
This idea is so popular that there's built-in methods to do it. For example:
list.addAll( Arrays.asList(strs) );
will add your array elements to an existing list. Also the Collections class (note the s at the end) has static methods that work for all Collection classes and do not require calling Arrays.asList(). For example:
Collections.addAll( list, strs );
Collections.addAll( list, "Larry", "Moe", "Curly" );
If you just want a list with only the array elements, you can do it on one line:
List<String> list = Arrays.asList( strs );
Edit: Many other classes in the Java API support this addAll() method. It's part of the Collection interface. Other classes like Stack, List, Deque, Queue, Set, and so forth implement Collection and therefore the addAll() method. (Yes some of those are interfaces but they still implement Collection.)
If you are using Java 9 then easily you can add the multiple String Objects into Array List Like
List<String> strings = List.of("abc","123","zzz");
If you want to stick to good practice, declare your Strings in an array:
String[] strs = new String[]{ "abc", "123", "aaa", ... };
for (String s : strs) // Goes through all entries of strs in ascending index order (foreach over array)
list.add(s);
If strX would be class fields then you could try using reflection - link to example of accessing fields and methods.
If it is local variable then you can't get access to its name so you will not be able to do it (unless str would be array, so you could access its values via str[i] but then you probably wouldn't need ArrayList).
Update:
After you updated question and showed that you have 100 variables
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
//...
String str100 = "zzz";
I must say that you need array. Arrays ware introduced to programming languages precisely to avoid situation you are in now. So instead of declaring 100 separate variables you should use
String[] str = {"abc", "123", "aaa", ... , "zzz"};
and then access values via str[index] where index is value between 0 and size of your array -1, which in you case would be range 0 - 99.
If you would still would need to put all array elements to list you could use
List<String> elements = new ArrayList<>(Arrays.asList(str));
which would first
Arrays.asList(str)
create list backed up by str array (this means that if you do any changes to array it will be reflected in list, and vice-versa, changes done to list from this method would affect str array).
To avoid making list dependant on state of array we can create separate list which would copy elements from earlier list to its own array. We can simply do it by using constructor
new ArrayList<>(Arrays.asList(str));
or we can separate these steps more with
List<String> elements = new ArrayList<>();//empty list
elements.addAll(Arrays.asList(str));//copy all elements from one list to another
Yes. The way to use a loop is not to declare 100 string variables. Use one array instead.
String[] str = new String[101];
str[1] = "abc";
str[2] = "123";
str[3] = "aaa";
....
str[100] = "zzz";
(I made the indexes go from 1 to 100 to show how it corresponds to your original code, but it's more normal to go from 0 to 99 instead, and to initialize it with an array initializer as in #markspace's answer.)
The following creates the ArrayList on the specific String values you have:
ArrayList<String> list1 = new ArrayList<String>() {{addAll(Arrays.asList(new String[]{"99", "bb", "zz"}));}};
Or, if it's just some distinct values you want, use this for say - 10 of them:
ArrayList<String> list2 = new ArrayList<String>() {{for (int i=0; i<10; i++) add(""+System.currentTimeMillis());}};
I have an ArrayList defined as:
ArrayList<String[]> params=new ArrayList<String[]>();
It contains parameters ("name", value) in String Arrays. I would like to insert elements in the ArrayList:
params.add({"param1", param1});
But when I try that I get an error.
What is the simplest way to add String Arrays in ArrayList. Do I have to declare a new array each time?
A declaration is the only time you can just use braces, e.g.
String[] test = {"param1", param1};
In all other times, you must use new String[] also.
params.add(new String[] {"param1", param1});
Make a string with some special sequence. Add it in ArrayList and then split it when you need it. For example:
ArrayList<String> str_list = new ArrayList<String>();
String str = "name&&&value";
// Add str to str_list
str_list.add(str);
Then fetch it from arraylist and split it using following code:
String str1 = str_list.get(index);
String[] values = str1.split("&&&");
values[0] will be name and values[1] will be value.
You should read up on ArrayLists here
But after initialization you can do this:
params.add("String");
params.add(aStringObject);
Your initialization is incorrect as well; If you want a ArrayList of Strings it should be:
ArrayList<String> params = new ArrayList<String>();
ArrayList<String> veri1 = new ArrayList<String>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
How can I add veri2 to veri1 like one element? I mean, if I call veri.get(0), it returns veri2.
You should declare your list as a list of string arrays, not a list of strings:
List<String[]> veri1 = new ArrayList<String[]>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
veri1.add(veri2);
Note that in general it is better to declare your list as List instead of ArrayList, as this leaves you the freedom to switch to a different list implementation later.
You should use the List interface and generics (for Java >= 1.5). Depending on what you want to do you can use this:
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
List<String> veri1 = new ArrayList<String>();
veri1.addAll(Arrays.asList(veri2)); // Java 6
List<String[]> veri3 = new ArrayList<String[]>();
veri3.add(veri2);
You can't actually do this.
veri2 is an array of strings, veri1 is an arraylist of individual strings
Thus, doing veri1.get(0) should return a single string, not an array of strings.
I just saw (due to fm), that you have an ArrayList<String>. You can do:
ArrayList veri1 = new ArrayList();
veri1.add(veri2)
or
ArrayList<String[]> veri1 = new ArrayList<String[]>();
veri1.add(veri2)
You can also make ver1 a List, which gives you flexibility in changing implementations.
It all depends on whether or not you want your ArrayList to be of one type or if you need it to hold multiple types.
If you just need it to hold String arrays throughout your code, declare as stated above:
ArrayList<String[]> list1 = new ArrayList<String[]>();
then just add the String array to it as follows:
list1.add(stringArray);
If you want it to be dynamic, declare it with the object type:
ArrayList<Object> anythingGoes = new ArrayList<Object>();
and then you can add anything later on as well:
anythingGoes.add(stringArray);
anythingGoes.add(myAge);
anythingGoes.add(myName);
I think you mean this:
import java.util.Arrays;
ArrayList<String> veri1 = new ArrayList<String>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
veri1.addAll(Arrays.asList(veri2);
You pretty much just need to add the array to the ArrayList.
ArrayList<String[]> veri1 = new ArrayList<String[]>();
String[] veri2 = {"a", "b", "c"};
veri1.add(veri2);
System.out.println(veri1.size());
for(String[] sArray : veri1)
for(String s : sArray)
System.out.println(s);