0

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

6
  • What happened when you tried get();? Commented Jul 7, 2014 at 20:20
  • @BitNinja I tryed this, dogName.get(i).getName(); it said it could not find the symbol. Commented Jul 7, 2014 at 20:22
  • 2
    That's because you used ArrayList dogeName = dogie.getAnimalList() instead of List<Animal> dogeName = dogie.getAnimalList() so you can access the objects stored inside the List only as an Object but not as an Animal. Commented Jul 7, 2014 at 20:23
  • look here: stackoverflow.com/questions/10259599/… Commented Jul 7, 2014 at 20:23
  • @yossico: That is a not a great link, the top answer doesn't even use generics. Commented Jul 7, 2014 at 20:25

1 Answer 1

0

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

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

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

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.