Results 1 to 3 of 3
  1. #1
    nn12 is offline Member
    Join Date
    Sep 2008
    Posts
    85
    Rep Power
    0

    Default Qustion about collections

    I have an List e.g
    Java Code:
    List<Object> userList = new ArrayList<Object>();
    userList is basically a collection of User objects and has been casted to Object due to some project need.

    My question: Is it possible to convert the entire userlist into List of User objects in one line or I will need to iterate through every object in the list, type cast into User object n add one by one.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,368
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by nn12 View Post
    I have an List e.g
    Java Code:
    List<Object> userList = new ArrayList<Object>();
    userList is basically a collection of User objects and has been casted to Object due to some project need.

    My question: Is it possible to convert the entire userlist into List of User objects in one line or I will need to iterate through every object in the list, type cast into User object n add one by one.
    Yup, you can do that (with a bit of old fashioned trickery ;-)

    Java Code:
    List<Object> listA= new ArrayList<Object>();
    List<String> listB= (List)listA;
    The compiler warns about the cast but there's nothing it can do about it because generic objects only exist during compile time (during runtime they're all just Lists). Not that the cast (List<String>) doesn't work and the compiler flags it as an error.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    nn12 is offline Member
    Join Date
    Sep 2008
    Posts
    85
    Rep Power
    0

Similar Threads

  1. Help collections
    By nikosv in forum New To Java
    Replies: 8
    Last Post: 12-13-2010, 05:29 PM
  2. Collections
    By Cbani in forum New To Java
    Replies: 3
    Last Post: 02-16-2010, 02:46 PM
  3. Collections Help
    By Dr Gonzo in forum New To Java
    Replies: 0
    Last Post: 12-07-2008, 09:15 PM
  4. Collections Sort
    By senthil_jr in forum Advanced Java
    Replies: 2
    Last Post: 06-04-2008, 08:11 AM
  5. Performance Of Collections
    By thomasprabu in forum Advanced Java
    Replies: 0
    Last Post: 01-05-2008, 11:17 AM

Posting Permissions

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