java - Am I not understanding ArrayList or am I missing something? -


i'm trying create very, simple program. want class called text print out string, specifically, 1 letter. in second class called window, want create arraylist of class, iterate through list , call method of text class print out string. not print anything.

what doing wrong?

public class text {      private string a;      public void printa() {         = "a";         system.out.print(a);     }  } 

and other class..

import java.util.arraylist;  public class window {      private arraylist<text> string = new arraylist<text>(5);      public window() {         addtext();     }      public void iterate() {         (int = 0; < string.size() - 1; i++) {             string.get(i).printa();         }     }      public void addtext() {         (int = 0; <string.size() - 1; i++) {             string.add(new text());         }     }      public static void main(string[] args) {         window wind = new window();         wind.iterate();     }  } 

if modify iterate to:

public void iterate(){     system.out.println(string.size()-1);     for(int = 0; < string.size()-1;i++){         string.get(i).printa();      } } 

you -1

let me explain why:

each arraylist instance has capacity. capacity size of array used store elements in list. @ least large list size. private arraylist<text>string = new arraylist<text>(5); merely sets capacity of underlying array data structure implement arraylist object. size() returns number of objects inside of arraylist not capcity

public void addtext(){     for(int = 0; <string.size()-1;i++){         string.add(new text());      } } 

the loop's expression doesn't evaluate true, , therefore never add single object loop why iterate print -1 if added print statement there


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -