简体   繁体   中英

Trying to get method inside ArrayList of Objects JAVA

I have created an ArrayList of objects and i am trying to call a method inside the ArrayList which would return the value of a string. Using a normal Array i can do this but not sure how to do this using an ArrayList, Below is the code:

import java.util.*;
public class Animal {

    public static void main(String[] args) {
       dog d = new dog("Ralph");
       AnimalList dogie = new AnimalList(d);
       ArrayList dogName = dogie.getAnimalList();


       for(int i=0; i<dogName.size();i++){
           System.out.println(dogName.get(i));
       }
    } 

The class that holds the method is as follows:

public class dog extends Animal{
   String dogName;
    public dog(String dogName)
    {
        this.dogName = dogName;
    }


    public String getName()
    {
        return dogName;
    }
}

I So am trying to using the getName() method to return the string at the index of the for loop, which then I can using in a System.print. I tryed to get .get(i) followed by the method name but it would not work.

Thanks

You don't need to write a new List class. Just specialize ArrayList to hold Animal s.

List<Dog> dogs = new ArrayList<>();

Now, dogs.get(i) returns a Dog . It has a getName method.

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