Reputation: 81
I'm very new to Java, and I would like your inputs.
So, I have an array:
String[] names = {"Anna", "Jo"};
String[] newNames = {"Bob", "Sue", "Jane"};
int totalLength = names.length + newNames.length;
String[] allNames = new String[totalLength];
And I am combining them through:
for (int i = 0; i < names.length; i++) {
allNames[i] = names[i];
}
for (int i = 0; i < newNames.length; i++}
allNames[i + names.length] = newNames[i];
}
My question is how do I set the allNames array into the original names array? Like, names would be "Anna", "Jo", "Bob", "Sue", "Jane". I know that there are methods that can do this, but how would you do it manually?
Upvotes: 7
Views: 14339
Reputation: 1
arrays, in Java, are objects. So, simply setting names = allNames actually has them pointing to the very same object (not separate identical copies). In other words, if you were to change "Sue" to "Suzy" in one, it would change it in the other. This is the simplest and most efficient way to do it, assuming you don't need to use them separately.
Upvotes: 0
Reputation: 4365
allNames
to names
: names = allNames;
System.out.println(Arrays.toString(names));
clone
method: names = allNames.clone();
System.out.println(Arrays.toString(names));
names = Arrays.copyOf(allNames, allNames.length);
System.out.println(Arrays.toString(names));
names = new String[allNames.length];
System.arraycopy(allNames, 0, names, 0, allNames.length);
System.out.println(Arrays.toString(names));
names = Arrays.stream(allNames).toArray(String[]::new);
System.out.println(Arrays.toString(names));
All variants will get the job done:
[Anna, Jo, Bob, Sue, Jane]
However, using first way you will just point reference of names
to allNames
. All other variants - new array will be created and populated with allNames
values. The last behavior is usually preferable.
Upvotes: 6
Reputation: 109613
There is the Arrays
class that provides functions for such things as copying. Java programmers will generally search the javadoc in the web, or maybe in the IDE.
The answer would be:
names = allNames;
But working so is quite inefficient, exchanging entire array values.
In this case, as in java arrays are fixed size, one would use a dynamic List or Set (for unique elements):
List<String> names = new ArrayList<>();
Collections.addAll(names, "Anna", "Jo");
List<String> newNames = Arrays.asList("Bob", "Sue", "Jane");
List<String> allNames = new ArrayList(names);
allNames.addAll(newNames);
Upvotes: 1
Reputation: 575
In general arrays have fixed size. When you resize an array you copy all the data into a new one. So there is no way to do this when you dont init them with a larger size. The methods from the other answers will probably do what you want, but they do not expand your original array.
Upvotes: 0
Reputation:
First and preferred option is:
name = (String[])ArrayUtils.addAll(names, newNames);
second one could be what you are doing just add:
name = newName;
after for
loops.
Upvotes: 9