1

I am a newbie to Java. I have an array of objects that have a string field. I can concatenate all of the strings into an string array by looping, but it's very inelegant.

int numObj = obj.length;
String[] strArray = new String[numObj];
for (int i = 0; i < numObj; i++) {
    strArray[i] = obj[i].strField;
}

Is there a way to concatenate that single field from all of the objects into a string array in one command? e.g.:

String[] strArray = (String[]){obj[].strField};

This doesn't work because obj[] is an array and so it doesn't have any fields, but using {obj.strField} doesn't work either, because there is no object called obj. BTW I really don't have to recast the field or do .toString() because it is already a string.

I looked at many, many of the other posts (but perhaps not enough?) related to this but I still could not figure this out. There are some that refer to converting an object array to a string array, but I don't think those posts mean converting a particular field in the objects, but the object itself, as an uncast type.

In MATLAB this would be trivial: strCellArray = {obj.strField}; would create a cell array of strings from all of the strFields in obj instantly.

Thanks for your help.

1
  • 2
    Sorry, you pretty much have to do the loop. This is an area where Java is a bit inelegant compared to some other languages. Java 8 or 9 or 10 may fix this. :-) Commented Jan 19, 2012 at 19:20

1 Answer 1

7

What you did is the only way. You don't have to create a variable for the length of the array, though. And using public fields is, 99.99% of the times, a very bad idea:

String[] strings = new String[objects.length];
for (int i = 0; i < objects.length; i++) {
    strings[i] = objects[i].getStringField();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the tip on keeping fields private.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.