0

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?

MKK
  • 1
  • 1
  • 3
    Use a `StringBuilder` instead, use its `append` method to add to it and then *after* the loop return its content using its `toString` method. – Federico klez Culloca Apr 26 '22 at 18:44
  • We can use string concatenation, e.g `info += ...` (but `info` must be initialized beforehand, e.g. with `String info = "";`). We can also use a [`StringBuilder`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuilder.html). --- A remark: we most probably do not want the `return` where it is right now. – Turing85 Apr 26 '22 at 18:44
  • Thank you so much for the help! I totally forgot about StringBuilder – MKK Apr 26 '22 at 18:58
  • See [my Answer](https://stackoverflow.com/a/31169001/642706) to a similar question, to see a diagram I made as an overview of the various textual data types in Java: `String`, `StringBuilder`, `StringBuffer`, `CharSequence`, and more. – Basil Bourque Apr 26 '22 at 20:10

1 Answers1

2

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
cyberbrain
  • 3,433
  • 1
  • 12
  • 22