连接多个 arraylist 的字符串内容 VALUES 。奇怪的问题
我有许多具有 String
对象的 Arraylists
,并且我需要连接这些值。
例如:
ArrayList finalList = new ArrayList();
ArrayList catMe = new ArrayList();
ArrayList x = new ArrayList();
x.add("Green");
x.add("Red");
ArrayList y = new ArrayList();
y.add(" Apple");
//......
catMe.add(x);
catMe.add(y);
concatContents(catMe); // Here i need to do
// some concatenation magic.
所以当打印 finalList
时:
finalList.get(0) // should show > "Green Apple"
finalList.get(1) // should show > "Red Apple"
我知道如果只有两个列表 X 和 Y,看起来很容易......但我需要它的 n 维。假设有第三个列表
ArrayList z= new ArrayList();
z.add(" USA");
z.add(" Canada");
catMe.add(z);
concatContents(catMe);
现在 FinalList 应该显示
Green Apple USA
Green Apple Canada
Red Apple USA
Red Apple Canada
我需要递归吗?但无法思考如何实施!有java高手有解决办法吗?
I have many Arraylists
having String
objects , and I have a requirement to concatenate there values.
Eg:
ArrayList finalList = new ArrayList();
ArrayList catMe = new ArrayList();
ArrayList x = new ArrayList();
x.add("Green");
x.add("Red");
ArrayList y = new ArrayList();
y.add(" Apple");
//......
catMe.add(x);
catMe.add(y);
concatContents(catMe); // Here i need to do
// some concatenation magic.
so when finalList
is printed:
finalList.get(0) // should show > "Green Apple"
finalList.get(1) // should show > "Red Apple"
I know it looks easy if there are only two list X and Y... but I need it for n dimensions. Say if there is 3rd list
ArrayList z= new ArrayList();
z.add(" USA");
z.add(" Canada");
catMe.add(z);
concatContents(catMe);
Now finalList should show
Green Apple USA
Green Apple Canada
Red Apple USA
Red Apple Canada
Do i need recursion? Unable to think how to implement though! Do any java master there have a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(4)
这是一个递归答案。只是煮熟了,所以质量没有保证......:)
Here's a recursive answer. Just cooked it up, so no guarantees on quality... :)
像这样的东西应该有效。 (我实际上并没有编译它,为了简单起见,将其写为伪代码。照顾泛型和正确的类型列表 List>)
编辑 - 好吧,上面的代码有点愚蠢,我没有正确理解这个问题。现在,随着其他人发布了递归解决方案,我认为通过发布非递归工作解决方案会得到回报。所以这是完全按照预期工作的
something like this should work. (I did not actually compile this, wrote it as sorta pseudo code for simplicity. take care of generics and proper types list List>)
EDIT -- okay so the code above was bit stupid, i had not understood the question correctly. Now as others have posted the recursive solutions, I thought would pay off by posting a non recursive working solution. So here is the one that works exactly as expected
快速而肮脏的解决方案:
给出:
Quick and dirty solution:
gives:
这是我的简单实现:
Here is my simple implementation: