0

I'm making a small program that simulates some of a bank's basic functions. I created a class Branch and used an ArrayList to hold Branch objects that the user would like to add. If I would like to specifically display all of the Branch names (one of the fields in the class) of each object contained in ArrayList<Branch>, would that be possible? Or is it better to create an array of strings that will hold each branch name? Currently, when I try to print out the ArrayList it outputs the pointer (I think) to the console.

I can put my code up upon request.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    This might help you: [Ways to iterate over a list in Java](https://stackoverflow.com/questions/18410035/ways-to-iterate-over-a-list-in-java) - Oh, and an extra array just to hold the names is a **horrible** idea. Don't create redundant duplicated data without very good reasons. – OH GOD SPIDERS Jun 22 '20 at 13:39
  • You have to override `toString()` method in `Branch` class. And you have to iterate over list to print single element of list. – Sudhir Ojha Jun 22 '20 at 13:40
  • 1
    You should show us what your code is, we'll be easier to help – Lê Hoàng Dững Jun 22 '20 at 13:42

2 Answers2

2

You basically answered it yourself. You just iterate over the ArrayList, and do stuff for each object.

For example, in a for-each-loop:

List<Branch> branchList = new ArrayList<Branch>();
for (Branch branch : branchList ) {
    // iterates through all your objects contained in the list
    // use the object here
}

Of course there are many more ways to do this, as it was already pointed out in a comment.

maloomeister
  • 2,461
  • 1
  • 12
  • 21
1

You need to iterate over your array to get the objects data. Here is some example with Java 8 streams:

List<Branch> branches = new ArrayList<Branch>();
// prints out the name of the object
branches.stream().map(branchName -> branch.getName()).forEach(System.out::println);

I found a nice blogpost which explains streams and how you can work with it. In my opinion the best way to work with Lists: https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/

Peacycode
  • 31
  • 4