You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Protocol Buffers:如何在proto文件中定义ArrayList<ArrayList<String>>消息

如何在Protobuf中定义嵌套的字符串列表(对应ArrayList<ArrayList>)

好问题!在Protocol Buffers里,并没有直接支持repeated repeated string这种嵌套重复字段的写法,要实现类似ArrayList<ArrayList<String>>的结构,我们需要借助嵌套消息来完成。

具体步骤很简单:

  1. 先定义一个内层消息,用来承载单个的字符串列表(对应外层列表里的每个ArrayList<String>)
  2. 在主消息中,用repeated修饰这个内层消息类型,就能得到嵌套的列表结构

下面是完整的示例代码:

// 内层消息:用来封装一组字符串,对应单个ArrayList<String>
message StringList {
  repeated string items = 1;
}

// 主消息:包含嵌套的字符串列表,对应ArrayList<ArrayList<String>>
message m1 {
  repeated StringList nested_mylist = 1;
}

补充说明

Protobuf的设计规则里,repeated只能修饰基本类型或消息类型,不能直接嵌套使用repeated。通过把内层的字符串列表封装成独立消息,就能完美实现多层嵌套的列表结构。

在生成的Java代码中,nested_mylist对应的类型就是List<StringList>,而每个StringList的items字段是List<String>,正好对应你需要的ArrayList<ArrayList<String>>(Protobuf默认的列表实现就是ArrayList)。

你可以根据业务场景调整消息和字段的命名,只要保证同一个消息内的字段号唯一即可。

内容的提问来源于stack exchange,提问作者Feihua Fang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:19:53