Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 01-02-2009, 02:46 AM
Member
 
Join Date: Jan 2009
Posts: 1
Rep Power: 0
natdizzle is on a distinguished road
Default vector - get
Hi,

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

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
Bookmark Post in Technorati
Reply With Quote
  #2 (permalink)  
Old 01-02-2009, 03:01 AM
Senior Member
 
Join Date: Jul 2007
Posts: 1,389
Rep Power: 3
hardwired is on a distinguished road
Default
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.
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 01-02-2009, 04:09 AM
Senior Member
 
Join Date: Dec 2008
Location: Hong Kong
Posts: 393
Rep Power: 1
mtyoung is on a distinguished road
Default
seems missing quot in third last line
should be return super.toString() + "[n: " + n + "]"; ?
__________________

To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.


To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
Bookmark Post in Technorati
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Vector problem Ace_Of_John New To Java 1 01-27-2008 08:53 PM
Vector help king_arthur New To Java 3 01-22-2008 07:33 PM
Declaring Vector mew New To Java 1 12-05-2007 08:14 PM
Vector Capacity JavaForums Java Blogs 0 12-03-2007 12:10 AM
Vector create Warren New To Java 3 11-19-2007 08:13 PM


All times are GMT +2. The time now is 03:10 AM.



VBulletin, Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2009, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org