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);
Related
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.
I am trying to add 100 (realistically more) Strings to an ArrayList. Instead of adding each String individually, how can I use something like a for loop to add them at once. The code below is an example.
ArrayList<String> strings = new ArrayList();
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
/*
More Strings created until the 100th String
.
.
.
*/
String s100 = "Kiwi";
//for loop to try add each String to List
for(int i=0; i<100; i++)
{
//Code to add each String to the arraylist
}
Can anyone identify the how I can add each String to the list?
Thanks much appreciated
Well, you could create a sophisticated strategy using reflection to fetch all variables of a given class and add them to a List; subsequently, you could loop this List and do whatever you want.
However, I do not think it would solve your problem. Indeed, you are likely to run into several pitfalls.
I would change your approach to the problem. Create a static List and add whatever you need there (or a Singleton, it depends how you want to manage this List). Once you have the list of objects you can loop it.
Cheers,
From your comments you are dealing with custom objects. Regardless of how you want to transfer data from the objects into your ArrayList, better to use a collection. The type of the collection will depend on the source of your object data. As the data is hard-coded you could use an array. Multiple variables like these
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
become
String[] fruitArray = {
"Apple",
"Banana",
"Pear"
...
};
Then to add:
for (String fruit: fruitArray) {
strings.add(fruit);
}
As already stated my comment above, a cleaner design would be to to use a single List<MyObject> to contain all objects in a DRY approach and just extract a String as needed.
Could anybody have a look at this snippet of code and and tell me if there is a way to amalgamate the two while statements into one?
public static void main(String[] args) throws IOException
{
BufferedReader fileInput;
fileInput = new BufferedReader(new FileReader("information.txt"));
int countOfClients = 0;
while (fileInput.ready())
{
fileInput.readLine();
countOfClients ++;
}
int totalClients = countOfClients ;
Client[] clientDetails = new Client[totalClients];
int clientNumber = 0;
while (fileInput.ready())
{
String currentLineOfText = fileInput.readLine();
String clientName = currentLineOfText.substring(0, 19);
String gender = currentLineOfText.substring(20,21);
char clientGender = gender.charAt(0);
int clientAge = Integer.parseInt(currentLineOfText.substring(22,24));
String clientInterests = currentLineOfText.substring(25);
clientDetails[clientNumber] = new Client(clientName, clientGender, clientAge, clientInterests);
clientNumber++;
}
The first while statement is reading all the lines in the text, so it knows how many elements in the object array it needs.
The array clientDetails of class Client[] is then created.
The second while statement populates that array.
Can I avoid using two while statements?
Note: This is for an assignment and I have to use arrays.
As they're all saying, use an ArrayList to store the items.
If memory is an issue, you can use ArrayList.toArray() to trim it down to the bare bones.
If efficiency is an issue, you probably shouldn't be reading from a file in the first palce.
You could use an ArrayList instead of an array and simply use:
list.add(new Client(...));
If you really need an array, you can always call:
Client[] array = list.toArray();
Why create an array ? Why not have one while loop that creates an ArrayList and then (if you need an array) extract the resultant array from that using ArrayList.toArray() ?
You can avoid two while loops by changing Client[] to ArrayList();
Example:
List<Client> clientDetails = new ArrayList<Client>();
int clientNumber = 0;
while (fileInput.ready())
{
String currentLineOfText = fileInput.readLine();
String clientName = currentLineOfText.substring(0, 19);
String gender = currentLineOfText.substring(20,21);
char clientGender = gender.charAt(0);
int clientAge = Integer.parseInt(currentLineOfText.substring(22,24));
String clientInterests = currentLineOfText.substring(25);
clientDetails.add( new Client(clientName, clientGender, clientAge, clientInterests));
}
Note: Hand edited, there may be syntax errors.
If you really can't use the pre-written ArrayList class, you could always effectively re-implement it (or at least the relevant bits of it) yourself.
The key technique is to take a guess at the size of the array you might need, define an array that size, and, if you find it is too small, create a bigger array and copy all the existing values from the old to the new array, before continuing in the space that is left over.
At the other end of the loop, you might be in for yet another step, and shrink the array again (by declaring a smaller array and copying values over) so you have no empty spaces left.
Or, as recommended by all the other answers, just use an ArrayList, which already does exactly this for you...
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);
}
}
I use the following code to convert an Object array to a String array :
Object Object_Array[]=new Object[100];
// ... get values in the Object_Array
String String_Array[]=new String[Object_Array.length];
for (int i=0;i<String_Array.length;i++) String_Array[i]=Object_Array[i].toString();
But I wonder if there is another way to do this, something like :
String_Array=(String[])Object_Array;
But this would cause a runtime error: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
What's the correct way to do it ?
Another alternative to System.arraycopy:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
In Java 8:
String[] strings = Arrays.stream(objects).toArray(String[]::new);
To convert an array of other types:
String[] strings = Arrays.stream(obj).map(Object::toString).
toArray(String[]::new);
System.arraycopy is probably the most efficient way, but for aesthetics, I'd prefer:
Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);
I see that some solutions have been provided but not any causes so I will explain this in detail as I believe it is as important to know what were you doing wrong that just to get "something" that works from the given replies.
First, let's see what Oracle has to say
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must
* allocate a new array even if this list is backed by an array).
* The caller is thus free to modify the returned array.
It may not look important but as you'll see it is... So what does the following line fail? All object in the list are String but it does not convert them, why?
List<String> tList = new ArrayList<String>();
tList.add("4");
tList.add("5");
String tArray[] = (String[]) tList.toArray();
Probably, many of you would think that this code is doing the same, but it does not.
Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;
When in reality the written code is doing something like this. The javadoc is saying it! It will instatiate a new array, what it will be of Objects!!!
Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;
So tList.toArray is instantiating a Objects and not Strings...
Therefore, the natural solution that has not been mentioning in this thread, but it is what Oracle recommends is the following
String tArray[] = tList.toArray(new String[0]);
Hope it is clear enough.
The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. The only downside is that it has to be from Iterable to Iterable but this is the way I would do it:
Iterable<Object> objects = ....... //Your chosen iterable here
Iterable<String> strings = com.google.common.collect.Iterables.transform(objects, new Function<Object, String>(){
String apply(Object from){
return from.toString();
}
});
This take you away from using arrays,but I think this would be my prefered way.
This one is nice, but doesn't work as mmyers noticed, because of the square brackets:
Arrays.toString(objectArray).split(",")
This one is ugly but works:
Arrays.toString(objectArray).replaceFirst("^\\[", "").replaceFirst("\\]$", "").split(",")
If you use this code you must be sure that the strings returned by your objects' toString() don't contain commas.
If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.
If you know your Object array contains Strings only, you may also do (instread of calling toString()):
for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];
The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:
Object[] o = new String[10];
String[] s = (String[]) o;
You can use type-converter.
To convert an array of any types to array of strings you can register your own converter:
TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {
#Override
public String[] convert(Object[] source) {
String[] strings = new String[source.length];
for(int i = 0; i < source.length ; i++) {
strings[i] = source[i].toString();
}
return strings;
}
});
and use it
Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
String[] strings = TypeConverter.convert(objects, String[].class);
For your idea, actually you are approaching the success, but if you do like this should be fine:
for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];
BTW, using the Arrays utility method is quite good and make the code elegant.
Object arr3[]=list1.toArray();
String common[]=new String[arr3.length];
for (int i=0;i<arr3.length;i++)
{
common[i]=(String)arr3[i];
}
Easily change without any headche
Convert any object array to string array
Object drivex[] = {1,2};
for(int i=0; i<drive.length ; i++)
{
Str[i]= drivex[i].toString();
System.out.println(Str[i]);
}