Results 1 to 2 of 2

Thread: Java OOP Question

  1. #1
    Senior Member
    Join Date
    Jan 2006
    Location
    Oop North
    Posts
    1,403
    Thanks
    2
    Thanked
    4 times in 4 posts

    Java OOP Question

    Hey

    This is probably really simple, and im sure I've seen this before, but I've been coding for the last 18 hours and my mind isn't working properly.

    I'm storing objects inside an arraylist in Java, and when i try to get them back out, they are being returned as type Object. How can I cast it back to the Class type, and get access to its accessor methods?

    Thanks

  2. #2
    Senior Member
    Join Date
    Jun 2006
    Posts
    340
    Thanks
    22
    Thanked
    14 times in 14 posts

    Re: Java OOP Question

    Either use generics so that get returns the object as the correct type (Java 1.5+):
    ArrayList<MyClass> array = new ArrayList<MyClass>();
    array.add(new MyClass());
    MyClass retrieved = array.get(0);

    Or cast it yourself:
    ArrayList array = new ArrayList();
    array.add(new MyClass());
    MyClass retrieved = (MyClass)array.get(0);

    I'd recommend using generics, as it'll make your code less error prone.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Not a very technical Question, but a Question none the less.
    By chip35 in forum Help! Quick Relief From Tech Headaches
    Replies: 6
    Last Post: 24-03-2007, 09:05 PM
  2. Potential HUGE source of free Java games / apps
    By PriestJPN in forum Smartphones and Tablets
    Replies: 4
    Last Post: 03-11-2004, 01:59 AM
  3. Java Web server / HTTP proto question
    By Purple in forum Software
    Replies: 9
    Last Post: 13-10-2004, 10:50 PM
  4. Java Problems
    By Applecrusher in forum Software
    Replies: 4
    Last Post: 27-04-2004, 01:12 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
  •