Java: How to set an array with another array? - java

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?

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.

Just assign allNames to names:
names = allNames;
System.out.println(Arrays.toString(names));
Or simply use clone method:
names = allNames.clone();
System.out.println(Arrays.toString(names));
Or use Arrays.copyOf:
names = Arrays.copyOf(allNames, allNames.length);
System.out.println(Arrays.toString(names));
Or use System.arraycopy:
names = new String[allNames.length];
System.arraycopy(allNames, 0, names, 0, allNames.length);
System.out.println(Arrays.toString(names));
Or with Java 8:
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.

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);

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.

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.

Related

Add multiple items to an array

So lets say I want to make an array of nine country names. I have the code to create the array:
String[] countryName = new String[9];
Lets say I wanted to add nine unique country names to this array. I could do something like this:
countryName[0] = "Mexico";
countryName[1] = "United States";
and so on. But is there a way I could add all of the names at once? Maybe something like an add() statement?
you can initialize the array with:
String[] countryName = new String[]{"Mexico", "Italy", "Spain"};
You can write simple utility method using varargs
static void addAll(String[] arr, String ... elements)
{
if (elements != null)
{
System.arraycopy(elements, 0, arr, 0, elements.length);
}
}
Usage
addAll(countryName, "Mexico", "US", "Ukraine");
Use an ArrayList this has the Add method.
ArrayList<String> countryName = new ArrayList<String>();
countryName.add("Mexico");
countryName.add("United States");
countryName.add("Dominican Republic");
countryName.add("...");
Enlist all contries in String and use split
String str="Country1,Country2,Country3";
String array[]=str.split(",");//You even don't need to initialize array
Use delimeter carefully to avoid extra spaces.
NOTE:
As this is one of the ways to add values to array but still I suggest you to go for Michel Foucault's answer as split will have more overhead than direct initialization.

How to "propagate" the sorting of an `ArrayList<String>` to another one?

I have multiple ArrayList<String>s "linked" into a custom adapter I'm using to build a list view.
Now suppose they are just two in total, to simplify.
I want to sort one of them and then have this new order reflected into the other one, in order to maintain the list consistent.
This is what I was thinking to do and doesn't work, ending with an IndexOutOfBoundsException: Invalid index 0, size is 0 at the line signed with *.
// initial declarations:
List<String> filenameEntries = new ArrayList<String>();
List<String> idEntries = new ArrayList<String>();
/* various operations that fill
the two ArrayList here... */
// sorting:
List<String> oldFilenameEntries = new ArrayList<String>();
List<String> oldIdEntries = new ArrayList<String>();
oldFilenameEntries = filenameEntries;
oldIdEntries = idEntries;
idEntries.clear();
Collections.sort(filenameEntries);
for (int i = 0; i < filenameEntries.size(); i++ ) {
for (int j = 0; j < oldFilenameEntries.size(); j++ ) {
if (oldFilenameEntries.get(j) == filenameEntries.get(i)) {
idEntries.add(oldIdEntries.get(j)); // *
}
}
}
My idea was to search into the old ArrayList for every element from the new one, and then use this "old" index to re-polulate the other ArrayList.
(I have the restriction that the other "sorted" ArrayList must be again idEntries. This is way I did this sort of transfer)
Any suggestion?
Thanks.
EDIT:
I thought it was a sorting issue and then came out I missed the right way to make a copy for the ArrayLists. Thanks to everyone that pointed out that the error was at
oldFilenameEntries = filenameEntries;
oldIdEntries = idEntries;
and why.
I accepted the answer that pointed me more quickly to the solution.
I removed the two lines above and changed the previous into
List<String> oldFilenameEntries = new ArrayList<String>(filenameEntries);
List<String> oldIdEntries = new ArrayList<String>(idEntries);
and from what I can see ATM all seems to work as expected.
The issue is the assignment: oldIdEntries = idEntries; this is causing both references to point to same list so when you do idEntries.clear(); you have cleared the one list to which both are pointing. You need to make a copy of the list not just assign the reference.
Collections.copy
Lists.copy
ImmutableList.copy()
The problem is in these 2 lines:
oldFilenameEntries = filenameEntries;
oldIdEntries = idEntries;
After this, both old... and original variables point to the same list. Then you call idEntries.clear(). This clears both idEntries and oldIdEntries since they point to the same list.
For this to work, you need to copy the list instead of just assigning it. You could use Collections.copy(). Here is an example:
Java Collections copy list - I don't understand
On a different note, this approach seems too complex - but it's also not very clear what you are trying to accomplish so I can't suggest a better way.
Iterate over the soreted list, clone each object and then add it to the new array list
Two issues:
One:
oldFilenameEntries = filenameEntries;
oldIdEntries = idEntries;
Now, both old and new entries point to the same list.
Then, idEntries.clear().
This clears both old and new entries.
If you want to do this somehow, use Collections.copy()
Two:
If you're just going to check for equality, I don't see why you need to have two for-loops, and have both sorted.
You could just do this:
for (int i = 0; i < filenameEntries.size(); i++ ) {
if (oldFilenameEntries.contains(filenameEntries.get(i)) {
idEntries.add(oldIdEntries.get(j)); // *
}
}
}
NOTE: as I don't know what the original point of your code was, and equality checking was all I could infer from your snippet, I'm suggesting this.

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.

Creating objects with names from string[]

Hey I'm having some trouble with Java (shocker (sarcasm)). I have an array of strings, and what I would like to do is iterate through the array, using each string to make a new object. Is this legal?
String[] arrayOfNames = String[3];
goGetNamesToFillTheArray();
for(i = 0; i < arrayOfNames.length; i++) {
Person arrayOfNames[i] = new Person();
}
If it's not legal for me to do that, how would I do something like that?
For clarification, I want to have several objects of type person. If the array contains the entries jon and sally, I could later later in the program have jon.doSomething() as well as sally.doSomething()
Assuming you want to create an array of Persons and filled them with the names:
String[] arrayOfNames = new String[3];
goGetNamesToFillTheArray();
Person[] arrOfPerson = new Person[arrayOfNames.length];
for(int i = 0; i < arrOfPerson.length; i++) {
arrOfPerson[i] = new Person(arrayOfNames[i]);
}
Several things:
String[] arrayOfNames = String[3];
is incorrect. You need to allocate memory via the new operator:
String[] arrayOfNames = new String[3];
To my knowledge, there's no way to dynamically create identifiers. I have a feeling that what you're actually trying to do is to use the name from your array and in some way use it in Person.
To do this, you can have your constructor take a String as its parameter. If you do this, you can change your code to be:
goGetNamesToFillTheArray();
Person[] people = new Person[3];
for(i = 0; i < 3; i++)
{
people[i] = new Person(arrayOfNames[i]);
}
NB:I used 3 in the above code since you did, but you should use a constant or some sort of variable, ie final int LENGTH = 3;.
You should show us the Person class. But conceivably this class will have a constructor that takes a String. Perhaps you should pass in the String from the array into the constructor.
Edit: as Ran Eldan shows you with his answer. 1+ to that answer!
Edit: Regarding your recent edit to your question:
You state:
For clarification, I want to have several objects of type person. If the array contains the entries jon and sally, I could later later in the program have jon.doSomething() as well as sally.doSomething()
You're trying to give variables the names of Strings, and you shouldn't try to do this as this is not how Java works. Variable names are not all that important and certainly not as important as you think they are, but rather object references are what really matter. If you need to associate an object with a String, use a Map, but I don't think you even need to do this. Just use an array or ArrayList. This same type of question has been asked here umpteen million times, and if you search a little for it, you'll find the same answers.
If the question is to create the Object from String class name, You can use code below:
String className = "InstanceFromString";
InstanceFromString test = (InstanceFromString)Class.forName(className).newInstance();
System.out.println(test);

Remove a specific string from an array of string

I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}

Categories