将ArrayList输出为String而不出现[,](括号) [英] Output ArrayList to String without [,] (brackets) appearing

查看:732
本文介绍了将ArrayList输出为String而不出现[,](括号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个ArrayList,需要以String形式返回.现在,我正在使用这种方法:

OK, so I have an ArrayList that I need to return as a String. Right now I am using this approach:

List<Customer> customers = new ArrayList<>();
List<Account> accounts = new ArrayList<>();


public String customerList() 
{
    String list = Arrays.toString(customers.toArray()); 
    return list;
}

public String accountList() 
{ 
    String account = Arrays.toString(accounts.toArray()); 
    return account;
}

这很好用,但是问题是我在文本两边得到了方括号.我得到的东西是这样的:

This works fine, but the problem is that I get brackets around the text. I am getting stuff like:

 Customer list:
 --------------
 [Name: Last, First
 , Name: Last, First
 , Name: Last, First
 ]

当我想要这样的东西时:

When I want something like this:

 Customer list:
 --------------
 Name: Last, First
 Name: Last, First
 Name: Last, First

但是,与类似的问题不同,我不只是想逐行输出.我需要将ArrayList存储在没有括号的字符串中,以便可以使用它.

However, unlike similar questions, I don't simply want to output line by line. I need to store the ArrayList in a String without the brackets so I can work with it.

编辑:应该注意,我希望它看起来像的那个逗号是通过其他类中的方法放置的:

It should be noted that the one comma in the version I want it to look like was placed there by a method in a different class:

public final String getName()  
    { 
        return getLast() + ", " + getFirst(); 
    }

通过修改给出的两个答案,我找到了一个完整的解决方案.很难确定哪个是答案",因为我发现两者都很有用,但是我可以选择地使用一个答案.

EDIT 2: I was able to find a complete solution by adapting the two answers I was given. It was difficult deciding which was the "answer" because I found both useful, but went with the one that I could use more selectively.

public String customerList() 
{
    String list = Arrays.toString(customers.toArray()).replace(", N", "N").replace(", N", "N");
    return list.substring(1,list.length()-1);
}

要删除括号,我使用了修改后的返回.删除逗号需要我集中注意每一行都以"N"开头的事实,但是这种方法的缺点是,如果我在此处更改它而忘记更改它,则代码会中断.尽管如此,它仍然可以解决我的特定问题,并且我总是可以根据需要在两个地方都对自己表示敬意.

To remove the brackets I used the modified return. Removing the comma required me to focus on the fact that each line will start with an "N", but the flaw in this approach is that the code would break if I forget to change it here if I change it there. Still, it solves my specific problem, and I can always notate to myself in both places as needed.

推荐答案

您可以尝试将'['和']'替换为空白

You could try to replace the '[' and ']' with empty space

String list = Arrays.toString(customers.toArray()).replace("[", "").replace("]", "");

这篇关于将ArrayList输出为String而不出现[,](括号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆