Results 1 to 3 of 3

Thread: vector - get

  1. #1
    natdizzle's Avatar
    natdizzle is offline Nathan Nelson
    Join Date
    Jan 2009
    Posts
    100
    Rep Power
    0

    Default vector - get

    Hi,

    I'm trying to return the name of an object that I have added to a vector. I'm using

    Java Code:
    Vector<animal> cats = new Vector<animal>();
    		cats.addElement(new cat(0));
    		System.out.println("Type of object " + cats.get(i));
    But this returns:
    Type of object arrayofobjects$cat@10b30a7

    And I need it to return something more like "Type of object: Cat"

    how can I do this?

    Thanks,
    Nate

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    import java.util.Vector;
    
    public class Test {
        public static void main(String[] args) {
            Vector<Animal> v = new Vector<Animal>();
            for(int i = 0; i < 3; i++) {
                v.add(new Cat(i));
            }
            for(int i = 0; i < v.size(); i++) {
                System.out.println(v.get(i));
            }
        }
    }
    
    class Animal {
        public String toString() {
            return getClass().getName();
        }
    }
    
    class Cat extends Animal {
       int n;
    
        public Cat(int n) {
            this.n = n;
        }
    
        public String toString() {
            return super.toString() + "[n: " + n + "]";
        }
    }
    Last edited by hardwired; 01-02-2009 at 07:13 AM. Reason: Added missing quote.

  3. #3
    mtyoung is offline Senior Member
    Join Date
    Dec 2008
    Location
    Hong Kong
    Posts
    473
    Rep Power
    6

Similar Threads

  1. Vector create
    By Warren in forum New To Java
    Replies: 4
    Last Post: 03-02-2010, 02:42 AM
  2. Vector problem
    By Ace_Of_John in forum New To Java
    Replies: 1
    Last Post: 01-27-2008, 08:53 PM
  3. Vector help
    By king_arthur in forum New To Java
    Replies: 3
    Last Post: 01-22-2008, 07:33 PM
  4. Declaring Vector
    By mew in forum New To Java
    Replies: 1
    Last Post: 12-05-2007, 08:14 PM

Posting Permissions

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