简体   繁体   中英

Java Iterate through a collection of classes and using their functions

i wanted to know how i can iterate through a collection of classes and be able to use the classes functions on every pass.

Im new to java and im much more familier with c++.

This is the collection i wish to iterate..

private ArrayList<Album> albumCollection;

and activate the following function

 get title

This is my current code...

//Lists all stored titles
private void ListAllTitles(){
    int size = albumCollection.size();
    for(int i=0; i < size; i++){
        System.out.println(albumCollection(i).getTitle());
    }
}

In order to access an element from a List , you need to use the get method:

System.out.println(albumCollection.get(i).getTitle());

Also note, you could use the for each loop to achieve this:

for (Album album : albumCollection) {
    System.out.println(album.getTitle());
}

This for each construct is simpler:

for (Album album : albumCollection)
{
     System.out.println(album.getTitle());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM