How to append data into a String list in Java - java

I am new to Java and Here is my code.
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
String[] onedata={"j","k","l"};
the thing I want to do here is that, I want to append the onedata into datas at last index value.
Please help let me know that how can I do this.

You can use an ArrayList because their sizes are mutable. For example:
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
List<String[]> datasList = new ArrayList<>(Arrays.asList(datas));
String[] onedata = {"j","k","l"};
datasList.add(onedata);
datas = datasList.toArray(new String[datasList.size()][]);

The things you are dealing with are arrays (String[]) and multidimensional arrays (String[][]) in Java, not lists. Their length is fixed. Therefore to append a new item to an array in such way that the length increases (so not by replacing the last item in the current array) you would need to create a new array with length n+1, assign the old values to the first n indices and then the new value to the index n+1.

Related

Change size of an array by an arraylist

One of the main Charucteristic of the Array is immutability(Size of the array cant be changed) but while i was practicing i found myself in this case :
We have an Array with specific size
String[] strArr = new String[1];
And ArrayList with Objects
ArrayList<String> list = new ArrayList<>();
list.add("Alex");
list.add("Ali");
list.add("Alll");
So when we try to convert the list to an array and assign it to strArr , like this
strArr = list.toArray(strArr);
for(String str : strArr ) {
System.out.println(str);
}
It works without a problem even if the size of the array doesnt equal the size of the list
So I JUST WANT TO KNOW HOW THIS IS POSSIBLE , WHEN THE SIZE OF THE ARRAY CANT BE CHANGED ?
New array allocated
strArray first references to a String array of size 1, when you do strArr = list.toArray(strArr);, you change the reference of strArray to a different array. So you are not changing the array size, you are only changing to which array now strArrays refers to.
Possibly you assume that list.toArral(strArr) modifies strArr but that's not the case, as you can read at the java documentation. It reads:
"If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list"
The important section for your case, is where the documentation says: "Otherwise, a new array is allocated", so, no array resize is done.
You can use
strArr = list.subList(0, strArr.length).toArray(strArr);
Basicaly, the List#subList(fromIndex, toIndex) creates a new List with the elements starting in the fromIndex up to toIndex (self-explaintory)
You can read more about in https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-
It changes the reference to a new object. You can check this by calling: System.out.println(strAttr) immediately after you first assign the variable and then again after you call strArr = list.toArray(strArr);

How can add an element to an array?

I wrote this code with a String array:
public static String[] prgmNameList = {"bbbbb", "aaaaa"};
My question is now, how can I add a new item to that array like this:
prgmNameList.add("cccc");
prgmNameList is an array. The size of an array object cannot be changed once it has been created. If you want a variable size container, use collections. For example, use an ArrayList :
List<String> prgmNameList = new ArrayList<String>(3);
prgmNameList.add("bbbb");
That said, if you insist on using an array, you will need to copy your initial array into a new array for each new element that you want to add to the array which can be expensive. See System#arrayCopy for more details. In fact, the ArrayList class internally uses an array that is expanded once it is full using System.arrayCopy so why reinvent the wheel? Just use an ArrayList
On simpler terms, note these following points:
Array size is always fixed.(In your example you fixed the array size to 2 by adding 2 elements)
Arrays operate based on index starting from '0' zero, like - prgmNameList[0] will return 1st element added in the array
Array size cannot be changed at any point of time. If you need size to be variable, choose one of List implementations
ArrayList is the best option for your need that can define itself as an 'Array that can shrink or grow'
Sample code:
public static List<String> prgmNameList= new ArrayList<String>();
prgmNameList.add("bbb");
prgmNameList.add("bbb");
prgmNameList.add("ccc");
prgmNameList.remove("bbb"); //Removes by object resolved by equals() method
prgmNameList.remove(2); //Removes by index
You have created an Array which can not grow as it's fixed in size.
You need to create a list in order to add new elements as shown below.
List<String> prgmNameList = new ArrayList<String>();
prgmNameList.add("aaaa");
prgmNameList.add("bbbb");
prgmNameList.add("cccc");
You have to use ArrayList like that
ArrayList<String> al = new ArrayList<>();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
if you want to use array as you did you have to know the number of elements that you want to add
String[] myList = new String[10];
and then
myList[4]="AA"
--
this is not possible to add to myList.
I explain you how ArrayList works and then you will understand.
ArrayList is an class that contains Array from objects. every time you add it check if it have place to store the data in the array if not it creates new array bigger and store the data.
So ArrayList this is the solution (or any other list)
if you want to add to myList you will have to implement arratList..
The method you are looking for is defined for a Collection, but you are using an array with an array initializer.
I suggest switching to the List:
public static List<String> prgmNameList= new ArrayList<>(Arrays.asList("bbbbb","aaaaa"))
Then you can call add on it because now it is a list.
Btw.: Try to prevent having mutable variables in static variables.

How to get an element from a String Array, if the String array itself is an element of an ArrayList?

Let me give you an example;
String[] one = {"one", "two"};
String[] two = {"bob", "lol", "hi"};
List<String[]> list = new ArrayList<String[]>();
list.add(one);
list.add(two);
Now, I want to get the 2nd string array (which is 'two') in list. I do this by:
list.get(2);
But, say if I wanted to get the 2nd element in the two String array in List ( Basically I want to get the string "lol" from list->two->lol).
Is this how you do it:
list.get(2).get(2)
Indices in Java (and in most programming languages) starts with 0, so if you want to access to the second element you must use the index 1:
list.get(0)[1];
Note that
list.get(0)
will return the first String[] array, and to access to an element of an array you have to use the syntax:
someArray[index]
Array starts with index 0. so you have to use list.get(i)[1]

Java add variable to string array

I have a small code that includes citynames which will be displayed.
Now a want a user can add names with a scanner, I know the code for the scanner but not how to add the variable.
Code I have:
String[] cityNames = { "Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren" };
System.out.println(Arrays.toString(cityNames));
No you cannot do it with a Array since the size is fixed , once it declared.
You are probably looking for Collections. Prefer to Use List interface with ArrayList implementation.
The reason is that the ArrayList is
Resizable-array implementation of the List interface.
List<String> cityNames = new ArrayList<>();
Now you have methods like add, remove, ... and many more useful methods on your cityNames List
You can use a List<String>, get the input value and add it:
List<String> cities = new ArrayList<>();
cities.add(userInput);
List is better to use than array as its length is modifiable.
Arrays have a fixed length. If the amount of Strings in your collection is variable, you´ll have to use a List.
You can add new element to array if index of new element less than the size of array.
arr[i]="some value" // to do this i < arr.length
If array is completely filled with elements when you assign new value to index previous value will override. You can't add more elements than the size of declared since array has fixed size.
Array is fixed size so you can't add the value to it if the size is already filled. For dynamic array use List instead of array.
Do like this
List<String> list = new ArrayList<String>(Arrays.asList("Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren" ));
list.add("new value1");
list.add("new value2");
It's better to use there set, which excludes duplicate entries automatically:
Set<String> cities = new HashSet<String>();
cities.addAll(Arrays.asList("Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren"));
then to add new city just call:
sities.add(newCity);
Scanner input = new Scanner(System.in);
List<String> cityNames = new ArrayList<String>();
//Add the city names to cityNames list...
cityNames.add(input.next());

Adding values to already initialized object array in Java?

I'm developing for the Android platform and, to simplify the question, I'm using pseudo-names for the entities.
I have an object array stuff[] of the class StuffClass[].
StuffClass stuff[]={
new StuffClass(Argument, argument, argument),
new StuffClass(argument, argument, argument)
};
I have an activity returning a result of three arguments that I want to then use to add a new object to stuff[]. I've done so as follows:
stuff[stuff.length]=new StuffClass(argument, argument, argument);
and I get ArrayOutOfBounds (Figured that would happen).
So how might I go about creating a new object in the stuff[] array?
Arrays are static you can't change size without creating a new one before. Instead of that you can use a dynamic data structure such as an ArrayList
Example:
List<MyType> objects = new ArrayList<>();
objects.add(new MyType());
Here you forget about array size.
Array in Java is little bit special, it's length is fixed when it's initialized, you can not extend it later on.
What you can do is to create a new array, and use System.arraycopy to generate a new array, here's the sample code:
String[] arr1 = new String[]{"a", "b"};
String[] arr2 = new String[3];
System.arraycopy(arr1, 0, arr2, 0, 2);
arr2[2] = "c";
You cannot increase the size of an existing array. Once it's created, the size of the array is fixed.
You will need to create another bigger array and copy the items from the old array to the new array.
A better alternative is to use an ArrayList. When you add items to an ArrayList, the capacity will grow behind the scenes if needed; you don't have to worry about increasing the size.
you can use the ArrayList to do this
arraylist.add(object);
in java arrays are fixed length. you need to initialise them with the desired length.
Consider using a Collection such as ArrayList which will handle everything for you.
List<StuffClass> myList = new ArrayList<>();
myList.add(...);
Lists support similar behaviour to arrays ie:
myList.set(i, elem);
myArray[i] = elem;
elem = myList.get(i);
elem = myArray[i];
len = myList.size();
len = myArray.length;
You can then convert the list to an array.
StuffClass[] myArray = myList.toArray(new StuffClass[myList.size()]);
If you don't want to use lists consider using System.arrayCopy to create a new array with more elements.
read here for a good description.

Categories