• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Generic ArrayList  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is a 2 part question.

I have two classes: animal and vehicle which I'll be instantiating as objects. Animal contains two instance variables: numLegs and animalName, and vehicle contains one instance variable: numTires, both classes contain getters and setters.

I have a generic class Box that holds either an animal or a vehicle.

Suppose I want to create an arraylist of boxes. Every box in said arraylist will hold exclusively type animal or exclusively type vehicle.

e.g: In the case of exclusively animals, this will look something to the effect of:
List<Box<Animal>> list = new ArrayList<Box<Animal>>();
list.add( new Box<Animal>( new Animal( "fluffy", 4 ) ) );

(1). What should the box class look like?

also, suppose I want to perform a getter on an animal from the list.
Such as: System.out.println(list.get(0).getName());

(2). how would I go about this properly?
 
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kevann smith wrote:
(1). What should the box class look like?

This forum is NotACodeMill so we generally won't just provide code for you. Why don't you give writing the class a try and let us know what trouble you are having with it. If you aren't sure where to start then have a look here: Java Generics Tutorial

kevann smith wrote:
also, suppose I want to perform a getter on an animal from the list.
Such as: System.out.println(list.get(0).getName());

(2). how would I go about this properly?

If you get from a List<Box<Animal>> you will get a Box<Animal>. How do you get the Animal out of the Box?
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kevann smith wrote:(2). how would I go about this properly?

What Steve said.

However, I would definitely recommend creating a Boxable interface (you might be able to think of a better name for it but, off the top of my head, I can't for the life of me think what else these two types would have in common), and have both classes implement it.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!