Results 1 to 8 of 8
Thread: Help with objects in ArrayList
- 02-21-2011, 11:23 AM #1
Help with objects in ArrayList
Hi, can someone please help.
I have 4 external classes called Cat, Dog etc.
My test program instantiates them i.e. Cat cat = new Cat();
Afterwards I placed them in an ArrayList called 'animals':
animals.add(cat);
""
"'
""
I then created an enhanced 'for' loop:
The idea is to loop through each object and call its public methods.
for(Obect obj : animals)
{
obj.methodName(); //(The idea is that obj represents 'cat')
}
This creates an error. Is it even possible?
Thanks in advance.Sorry, I only speak machine language. Yes or a No?:confused:
- 02-21-2011, 11:29 AM #2
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 8
Yes, if you define an "Animal" base class and have them extend that (or interface and have them implement that) and then use that class/interface instead of "Object".
- 02-21-2011, 11:39 AM #3
The four external classes in the ArrayList all extend and implement an abstract class called Animal. I cannot create an instance of Animal as it is abstract.
Sorry, I only speak machine language. Yes or a No?:confused:
- 02-21-2011, 11:43 AM #4
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 8
No, but you can reference one. Try it. Change Object to Animal both in the generics definition of the List, and in the for loop.
- 02-21-2011, 11:47 AM #5
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,606
- Blog Entries
- 7
- Rep Power
- 17
- 02-21-2011, 11:50 AM #6
I've now got:
for(Animal : animals)
{
System.out.print("This is: "); Animal.describe();
}
Error: incompatible types
required: Animal
found: java.lang.Object
Don't know if I've got this right.Sorry, I only speak machine language. Yes or a No?:confused:
- 02-21-2011, 11:53 AM #7
- 02-21-2011, 11:55 AM #8
Java Is A Funny Language... Really!.gif)
Click on * and add to member reputation, if you find their advices/solutions effective.
Similar Threads
-
ArrayList duplicated/replaced objects
By ImAFycus in forum New To JavaReplies: 3Last Post: 05-29-2010, 07:58 PM -
arraylist help please? trying to add objects to an array list
By zhangster in forum New To JavaReplies: 9Last Post: 02-10-2010, 03:19 AM -
How can i store ArrayList objects in Access database
By frankycool in forum Advanced JavaReplies: 3Last Post: 11-04-2009, 06:55 AM -
Retrieving specific objects from ArrayList
By soketti in forum New To JavaReplies: 49Last Post: 10-29-2009, 07:10 AM -
ArrayList with different objects? Help
By xtrmi in forum New To JavaReplies: 4Last Post: 02-27-2009, 08:51 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks