Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add string to String array [duplicate]

Tags:

java

I am new in Java so I need little help

I have

String [] scripts = new String [] ("test3","test4","test5"); 

and I want to add new strings ( string1,string2) to this array ( scripts) for examples

String string1= " test1" String string2 = "test2" 

I want to add the new string not in the init but in later phase

How I can do it ?

like image 815
user1365697 Avatar asked Dec 31 '12 05:12

user1365697


People also ask

How do you add a string to an array?

Way 1: Using a Naive Approach Get the string. Create a character array of the same length as of string. Traverse over the string to copy character at the i'th index of string to i'th index in the array. Return or perform the operation on the character array.

How do you copy an array of strings?

convert Arrays to List using Arrays. Create temporary HashSet to store unique elements of List. Iterate through List using traditional for-loop. Try to add each elements of List to Set using add() method of Set. If return value of add() method is false then it is duplicate.


1 Answers

You cannot resize an array in java.

Once the size of array is declared, it remains fixed.

Instead you can use ArrayList that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.

ArrayList<String> ar = new ArrayList<String>(); String s1 ="Test1"; String s2 ="Test2"; String s3 ="Test3"; ar.add(s1); ar.add(s2); ar.add(s3);  String s4 ="Test4"; ar.add(s4); 
like image 70
Abubakkar Avatar answered Oct 06 '22 23:10

Abubakkar