java put string array into another string array constructor - java

I'm quite new to Java, and I'm not sure about is it possible to do something like below and how to do it with code.
String[] a = {"a", "b", "c", ...}; //unknown amount of elements
String[] b = new String[]{ //I want to put a's element in here assume I don't know what's the length of a };
Any idea of what I can put inside the braces after the constructor to initialize the string array b.
p.s. I'm not allowed to use string array a directly and must use constructor to declare string array b. I'm not allowed to use ArrayList.
Thanks!

The most concise way would be:
String[] b = Arrays.copyOf(a, a.length);

Use array copy to do the task.
Its prototype is:-
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
String[] a = {"a", "b", "c", ...}; //unknown amount of elements
String []b=new String[a.length];
System.arraycopy(a,0,b,0,a.length);

Related

Is there a more efficient way to add to an Array?

Below is a sample of code I am using to add to an array. Basically if I understand correctly currently I am copying an Array into a List, then adding to the list and copying back to an array. It seems like there should be a better way to do this.
List<String> stringList = new ArrayList<String>(Arrays.asList(npMAROther.getOtherArray()));
stringList.add(other);
npMAROther.setOtherArray(stringList.toArray(new String[0]));
I just edited my question for a bit more clarity. The for loop previously seen wasn't exactly needed in regards to my original question. I am simply looking for a more efficient way to add to an array.
If this is something that is done frequently, consider using a list. However...
You can easily add a single element to the end of an array like this.
final String[] source = { "A", "B", "C" };
final String[] destination = new String[source.length + 1];
System.arraycopy(source, 0, destination, 0, source.length);
destination[source.length] = "D";
for(final String s : destination) {
System.out.println(s);
}
You can also make it a method.
public static String[] addToArray(final String[] source, final String element) {
final String[] destination = new String[source.length + 1];
System.arraycopy(source, 0, destination, 0, source.length);
destination[source.length] = element;
return destination;
}
Supposing you want to use an array, not a list and that all the array elements are filled, you would copy the array in an array that has the size of the original array plus the string list size, then append the list elements at the end of the array:
String[] array = npMAROther.getOtherArray();
List<String> listElementsToAppend = marOther.getOtherListList();
int nextElementIndex = array.length;
// Increase array capacity
array = Arrays.copyOf(array, array.length + listElementsToAppend.size());
// Append list elements to the array
for (String other : listElementsToAppend) {
array[nextElementIndex++] = other;
}
There are many ways to combine arrays in O(N) time. You could do something more readable than your code, for instance :
String[] arr1 = {"1", "2"}, arr2 = {"3", "4"};
ArrayList<String> concat = new ArrayList<>(); // empty
Collections.addAll(concat, arr1);
Collections.addAll(concat, arr2);
// concat contains {"1", "2", "3", "4"}

How to pass array of string and a string as a vararg?

I want to pass an array and a single object to method which has varargs.
However, the most obvious solution doesn't seem to work:
public static final String[] ARRAY_ARGS = {"first argument", "second argument"};
public static String additionalArgument = "additional argument";
public static void foo(String... args) {
// ...
}
public static void main(String[] args) {
foo(ARRAY_ARGS,additionalArgument); // error! won't compile
}
How can I fix this?
A variable argument is equivalent to an array. Hence, the compiler does not accept an array and a string. One solution is to create an array from the original with the additional string added to it:
List<String> originalList = Arrays.asList(ARRAY_ARGS);
List<String> list = new ArrayList<String>(originalList);
Collections.copy(list, originalList);
list.add(additionalArgument);
foo(list.toArray(new String[list.size()]));
The Collections.copy is needed because adding to the list returned by Arrays.asList throws a java.lang.UnsupportedOperationException as the latter returns a list that extends AbstractList which does not support adding elements.
Another solution is to create a new array and individually add the elements:
String[] arr = new String[3];
arr[0] = ARRAY_ARGS[0];
arr[1] = ARRAY_ARGS[1];
arr[2] = additionalArgument;
foo(arr);
Or you can simply call foo with the individual parameters:
foo(ARRAY_ARGS[0], ARRAY_ARGS[1], additionalArgument);
You can do this, if the first argument to your method is the single string, followed by the varargs:
public static void foo(String a, String... args) {
System.out.println("a = " + a);
System.out.println("args = " + Arrays.toString(args));
}
Then calling foo("a", "b", "c") prints
a = a
args = [b, c]
The argument String ... args is shorthand for String[]. Therefore you get an error when you are calling foo(args,additionalargument) since the method declaration of foo is foo(String[] str) instead of foo(String[],String).
If you must distinguish between the array and the single string, concatenate the array values in a format you can "recognize", pass the "array-string" and the single string as parameters to the main method, and then parse the "array-string" in the relevant (foo) method.
A Java 8 approach to solve this problem is the following oneliner:
foo(Stream.concat(Arrays.stream(ARRAY_ARGS), Stream.of(additionalArgument)).toArray(String[]::new));
This creates a new String[] that can be passed to foo. Furthermore, foo must be made static, otherwise the code will not compile.
The only parameters that you can pass to the foo-method is either a String array or a bunch of individual Strings.
Simple yet elegant solution using Apache Commons Lang library:
foo(ArrayUtils.addAll(ARRAY_ARGS,additionalArgument));

add elements to Java Array

Let's say we defined an array with 20 elements. is there any way we can add some objects to the array, without any specific order of course and not just once like String[] t= {"one", "two", ..., "twenty"} ?
String[] t = new String[20];
//I know this won't work
//but something like this:
//t = {"one", "two", "three"}
//and later, add some more
//t = {"four"} ...
There are several ways to initialize the elements in an Array,
String[] t = new String[20];
t[0] = "zero";
t[1] = "one";
You can also use System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) to copy from one to another (if that's what you mean). Here concatenate Array(s) a and b to a new Array c.
String[] a = {"Hello"};
String[] b = {"World"};
String[] c = new String[a.length+b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
System.out.println(Arrays.toString(c));
Output is
[Hello, World]
You cannot change the size of the array, but you can assign elements at specific positions.
t[3] = "four";
Re-ordering and remembering where the array is supposed to end may or may not become cumbersome.
For more flexible "arrays", people like to use java.util.ArrayList.
You can assign values like this
t[10] = "ten";
t[11] = "eleven";
It is better to use ArrayList so there is no need of initializing the size first and it is dynamic too.
Unfortunately, that's not exactly how java arrays work. To instantiate and initialize an array use the syntax...
String[] t = new String[20];
t[0] = "One";
t[1] = "Two";
or,
String[] t = {"One", "Two"};
If you want more control over the array the I'd recommend using an ArrayList object instead where you can add, remove, change, sort the items in the array. For example,
ArrayList t = new ArrayList();
t.add("One");
t.add("Two");
t.remove(0);
ArrayList is a good option for ArrayList supports dynamic arrays that can grow as needed.
With arrays you can add elements by specifying the specific position you want to add
like adding in position 4 we can do something like array[3] = "four"
but for more control arraylist is recommended
Unfortunately, Array should be used in below way only
String[] t = new String[20];
t[0] = "One";
t[1] = "Two";
...
t[19] = "Twenty";
You can try using arrayList: You need not even specify how many elements are expected while initializing.
ArrayList t = new ArrayList();
t.add("One");
t.add("Two");
...
t.add("Twenty");

Recursive function that return string array (JAVA)

I need some help in JAVA:
I have a function signature which I can't change, and my function needs to be recursive and to return String array without any option to add it to the signature.
This is the signature I've got:
public String[] findSimilar(String w, int index, int k)
The function looks for similar words in a TRIE structure, with a difference of K letters changes between them.
For example- in a TRIE withe the words hello, nice, nine, cry, for the word "bike" and k=2, the function will return a String[] with nice and nine.
I'm not looking for a solution, just for a method to return string array.
** I wrote a function with the signature I've received as a wrapper, but I just found out that I can't use wrapper.
Thank you!
The trivial example:
public String[] findSimilar(String w, int index, int k) {
return new String[] {"string1","string2"}
}
Maybe more useful:
public String[] findSimilar(String w, int index, int k) {
List<String> similar = new ArrayList<>();
// insert some implementation here
return similar.toArray(new String[similar.size()]);
}
I'm not looking for a solution, just for a method to return string array.
To return a string array with literals string1 and string2 you could just use an array initializer such as return new String[] { "string1", "string2"};
Else, you could just create the String array and assign values to its positions if you know beforehand how many elements you will be returning:
String[] arr = new String[2];
arr[0] = "string1";
arr[1] = "string2";
return arr;
If it's the return type of a recursive function, you'll probably need to use the result from the recursive call to build your own result in the current call. Taking into account arrays cannot be extended, you'll need to create a new one with the expected size, and copy the values of the result into it for instance with System.arraycopy.
Use something like this.
I would not like to provide full code just an idea
public String[] findSimilar(String w, int index, int k) {
String[] res1=findSimilar(conditions one);
String[] res2=findSimilar(conditions two);
String[] res=new String[res1.length+res2.length];
//use public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
System.arraycopy(copyFrom, ..., copyTo, ..., ...);
}

difference between new String[]{} and new String[] in java

I am fresher in java ,i have a doubt in java
that is
String array= new String[]{};
what is the use of { } here ?
what is the difference between String array=new String[]; and String array=new String[]{};
when I am writing String array=new String[10]{}; got error why?
Help me I am confused.
{} defines the contents of the array, in this case it is empty. These would both have an array of three Strings
String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};
while [] on the expression side (right side of =) of a statement defines the size of an intended array, e.g. this would have an array of 10 locations to place Strings
String[] array = new String[10];
...But...
String array = new String[10]{}; //The line you mentioned above
Was wrong because you are defining an array of length 10 ([10]), then defining an array of length 0 ({}), and trying to set them to the same array reference (array) in one statement. Both cannot be set.
Additionally
The array should be defined as an array of a given type at the start of the statement like String[] array. String array = /* array value*/ is saying, set an array value to a String, not to an array of Strings.
String array=new String[]; and String array=new String[]{}; both are invalid statement in java.
It will gives you an error that you are trying to assign String array to String datatype.
More specifically error is like this Type mismatch: cannot convert from String[] to String
You have a choice, when you create an object array (as opposed to an array of primitives).
One option is to specify a size for the array, in which case it will just contain lots of nulls.
String[] array = new String[10]; // Array of size 10, filled with nulls.
The other option is to specify what will be in the array.
String[] array = new String[] {"Larry", "Curly", "Moe"}; // Array of size 3, filled with stooges.
But you can't mix the two syntaxes. Pick one or the other.
TL;DR
An array variable has to be typed T[]
(note that T can be an arry type itself -> multidimensional arrays)
The length of the array must be determined either by:
giving it an explicit size
(can be int constant or int expression, see n below)
initializing all the values inside the array
(length is implicitly calculated from given elements)
Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.
Replies
1. String[] array= new String[]{}; what is the use of { } here ?
It initializes the array with the values between { }. In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0.
2. what is the diff between String array=new String[]; and String array=new String[]{};
The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:
new String[] // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0] // size is known, it has 0 elements, explicitly sized
3. when am writing String array=new String[10]{}; got error why ?
(Again, ignoring the missing [] before array) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}.
Just make up your mind and use one of those - Java thinks.
help me i am confused
Examples
String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2
(Here, "same as" means it will construct the same array.)
Try this one.
String[] array1= new String[]{};
System.out.println(array1.length);
String[] array2= new String[0];
System.out.println(array2.length);
Note: there is no byte code difference between new String[]{}; and new String[0];
new String[]{} is array initialization with values.
new String[0]; is array declaration(only allocating memory)
new String[10]{}; is not allowed because new String[10]{ may be here 100 values};
String array[]=new String[]; and String array[]=new String[]{};
No difference,these are just different ways of declaring array
String array=new String[10]{}; got error why ?
This is because you can not declare the size of the array in this format.
right way is
String array[]=new String[]{"a","b"};
1.THE USE OF {}:
It initialize the array with the values { }
2.The difference between String array=new String[]; and String array=new String[]{};
String array=new String[]; and String array=new String[]{}; both are
invalid statement in java.
It will gives you an error that you are trying to assign String array
to String datatype. More specifically error is like this Type
mismatch: cannot convert from String[] to String
3.String array=new String[10]{}; got error why?
Wrong because you are defining an array of length 10 ([10]), then
defining an array of length String[10]{} 0
Theory above is well explained.
A PRACTICAL USE: Declare an array on the spot for a method parameter.
MyResult result = myMethod(new String[]{"value1", "value2"});

Categories

Resources