Results 1 to 4 of 4
  1. #1
    hamza is offline Member
    Join Date
    Jan 2014
    Posts
    2
    Rep Power
    0

    Post Can I use vector of an object to store multiple types of objects that extends that o

    Can I use vector of an object to store multiple types of objects that extends that object , say i have a class animal and two classes cat and dog , and i created a vector<animal> , and i want to do : add(new dog()) ,and add(new cat()) , is that possible ?

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,028
    Rep Power
    4

    Default Re: Can I use vector of an object to store multiple types of objects that extends tha

    As long as class Dog and Cat extend Animal you can. What happened when you tried?
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,912
    Rep Power
    5

    Default Re: Can I use vector of an object to store multiple types of objects that extends tha

    And check the API for Vector and ArrayList. Vector is synchronized and ArrayList isn't so use ArrayList if you don't need synchronization.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    hamza is offline Member
    Join Date
    Jan 2014
    Posts
    2
    Rep Power
    0

    Default Re: Can I use vector of an object to store multiple types of objects that extends tha

    thank you , i solve it ,
    this is the solution :
    Vector <? super animal> v = new Vector<animal>();
    v.add(new dog());
    v.add(new cat());
    and to know if the element is a cat or a dog :
    if (v.elementAt(i) instanceof cat) { cat c1 = (cat)v.elementAt(i); }

Similar Threads

  1. Multiple values of different types in an object
    By scheffetz in forum New To Java
    Replies: 2
    Last Post: 03-23-2011, 09:34 PM
  2. Sorting/Searching Objects with multiple types.
    By gcampton in forum New To Java
    Replies: 20
    Last Post: 10-22-2009, 12:58 AM
  3. Multiple types in Vector - type checking
    By Excession in forum Advanced Java
    Replies: 5
    Last Post: 07-13-2008, 08:06 PM
  4. Can I store multiple objects in an array
    By lareauk in forum New To Java
    Replies: 9
    Last Post: 05-29-2008, 04:57 AM
  5. Can I use vectors to store multiple types of objects
    By Nathand in forum Advanced Java
    Replies: 6
    Last Post: 04-28-2008, 08:55 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •