Reputation: 37
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.
Upvotes: 0
Views: 56
Reputation: 37
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!
Upvotes: 1