0

Im having a problem with my for loop for iterating over an ArrayList that hold objects. I make an ArrayList that hold these items, LumberItem is just a String for the name and an int for the amount.

ArrayList<LumberItem> lumberList = new ArrayList<LumberItem>();

LumberItem wood1 = new LumberItem("Oak", 1500);
lumberList.add(0, wood1);
LumberItem b = new LumberItem("Pine", 1500);
lumberList.add(1,b);
LumberItem c = new LumberItem("Cedar", 1500);
lumberList.add(2, c);
LumberItem d = new LumberItem("Maple", 1500);
lumberList.add(3, d);
LumberItem exp = new LumberItem("Birch", 1500);
lumberList.add(4, exp);

I try to use a for loop like so

for(int i = 0; i < lumberList.size(); i++) {
    contentTA.setText(lumberList.get(i).getType());
    contentTA.append("\n at index" + i + "\n");
}

My output consists of only the last element in my ArrayList so, Birch is outputted. I have tried using different methods of looping like

for(LumberItem l : lumberList)

I am still at the end of my ArrayList when I try and output. I wondering why this is happening since I haven't figured it out.

0

1 Answer 1

1

So I'm an idiot, I was using .setText() which will clear the JTextArea every time I call it, so it should be .append()!

for(LumberItem L : lumberList) {
    contentTA.append("\n" + L.getType());
}

or

for(int i = 0; i < lumberList.size(); i++) {
contentTA.append(lumberList.get(i).getType());

Will work. Hopefully my poor reading skills help out someone else!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.