MKK
MKK

Reputation: 1

How to add info from different locations in arrayList to a single string

I am trying to create a method which returns a single String (not String array) containing information for all objects in my array list. I know that strings are immutable so I am really struggling with how to add information from each object.

This is my method where I am trying to return a single string:

public String infoForEachItem ()
{
    String info;
    for (int y =0; y < items.size(); y++)
    {
        info = "ID: " + items.get(y).getId() + "\n" +
                "Name : " + items.get(y).getName() + "\n" +
                "Cost: " + items.get(y).getCost() + "\n";
        return info;
    }
}

As you can see, I want to create a string containing the Id, name, and cost of EACH item as a single string. It won't let me return within a for loop. Is there anyway to append something to the end of String?

Upvotes: 0

Views: 30

Answers (1)

cyberbrain
cyberbrain

Reputation: 5135

StringBuilder

Use StringBuilder to build up text by appending multiple times.

Here is some code expanding on comment by Federico klez Culloca:

public String infoForEachItem ()
{
    StringBuilder result = new StringBuilder();
    for (Item item : items) {
        result.append("ID: ").append(item.getId()).append('\n');
        result.append("Name: ").append(item.getName()).append('\n');
        result.append("Cost: ").append(item.getCost()).append("\n\n");
    }
    return result.toString();
}

You can chain the calls to .append as you think it is suitable, and there are overloads of the method for many parameter types.

Upvotes: 2

Related Questions