连接 Java 对象数组中的字段

发布于 2024-12-28 10:22:28 字数 779 浏览 0 评论 0原文

我是 Java 新手。我有一个包含字符串字段的对象数组。我可以通过循环将所有字符串连接到一个字符串数组中,但这非常不优雅。

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

有没有一种方法可以在一个命令中将所有对象中的单个字段连接到字符串数组中?例如:

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

这不起作用,因为 obj[] 是一个数组,因此它没有任何字段,但使用 {obj.strField} 也不起作用,因为没有名为 obj 的对象。顺便说一句,我真的不需要重新转换字段或执行 .toString() 因为它已经是一个字符串。

我查看了很多很多与此相关的其他帖子(但可能还不够?),但我仍然无法弄清楚这一点。有一些文章提到将对象数组转换为字符串数组,但我不认为这些帖子意味着将对象中的特定字段转换,而是将对象本身转换为非强制转换类型。

在 MATLAB 中,这很简单:strCellArray = {obj.strField}; 将立即从 obj 中的所有 strField 创建一个字符串元胞数组。

感谢您的帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

多像笑话 2025-01-04 10:22:28

你所做的是唯一的方法。不过,您不必为数组的长度创建变量。 99.99% 的情况下,使用公共字段是一个非常糟糕的主意:

String[] strings = new String[objects.length];
for (int i = 0; i < objects.length; i++) {
    strings[i] = objects[i].getStringField();
}

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文