Results 1 to 4 of 4
  1. #1
    Nosrettap is offline Member
    Join Date
    Jan 2011
    Posts
    13
    Rep Power
    0

    Default Copy a List<Integer> to an ArrayList

    Hi,

    I want to copy a List<Integer> to an ArrayList<Integer> but I can't seem to be able to do so...I don't want to cast it...Below is my code...Please help


    List<Integer> data = some data;
    ArrayList<Integer> dataCopy = new ArrayList<Integer>();
    Collections.copy(dataCopy, data);


    I keep getting the following exception:

    Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest

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

    Default

    Let an ArrayList constructor do the job:

    Java Code:
    ArrayList<Integer> dataCopy = new ArrayList<Integer>(data);
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Nosrettap is offline Member
    Join Date
    Jan 2011
    Posts
    13
    Rep Power
    0

    Default

    Thanks a billion

  4. #4
    goldest's Avatar
    goldest is offline Senior Member
    Join Date
    Oct 2009
    Location
    Pune, India
    Posts
    469
    Rep Power
    5

    Wink

    Even you can use the addAll(Collection c) method of ArrayList as well. Something like,
    Java Code:
    dataCopy.addAll(data);

    Goldest
    Java Is A Funny Language... Really!
    Click on * and add to member reputation, if you find their advices/solutions effective.

Similar Threads

  1. List and ArrayList
    By ravian in forum New To Java
    Replies: 3
    Last Post: 07-27-2011, 05:05 PM
  2. Replies: 1
    Last Post: 05-20-2010, 10:17 PM
  3. arraylist to integer array
    By monika in forum Advanced Java
    Replies: 3
    Last Post: 04-26-2010, 09:09 PM
  4. Linked List integer list
    By igniteflow in forum Advanced Java
    Replies: 1
    Last Post: 12-10-2008, 08:53 PM
  5. How to access ArrayList in List of List?
    By alvations in forum New To Java
    Replies: 5
    Last Post: 10-08-2008, 12:23 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
  •