-3

I have an arraylist of model class type where model class has some data. I want to copy the contents of this arraylist to another same type of arraylist but just upto starting 8 index. How to do this?

Lakshya Punhani
  • 273
  • 1
  • 5
  • 17
  • 4
    https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#subList(int,%20int) – dymmeh Jul 24 '17 at 14:43
  • write a loop that runs for 8 iterations and copy the elements over by referencing index by index – ja08prat Jul 24 '17 at 14:44
  • A little search and doc reading should get you there pretty fast. I'm really inclined to close this question. – Thomas Jul 24 '17 at 14:46

2 Answers2

1

How about List::sublist?

 ArrayList<YourType> al = initializeList();
 ArrayList<YourType> newList = new ArrayList<YourType>(al.subList(0, uptoThisIndex));

It allows getting a view of the list between two indices.

If you set the first index to 0 you get the result you desire.

Community
  • 1
  • 1
Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
  • You don't need to instanciate a new ArrayList, just do newList = al.subList(0, uptoThisIndex) – Denis Jul 24 '17 at 15:36
  • 1
    @Denis OP needs a copy of the original list. sublist returns a view. Modifying the view means modifying the original list. – Davide Spataro Jul 24 '17 at 15:40
0

You can also do it like this:

    ArrayList <YourDataType> arrayList1 = new ArrayList<YourDataType>();
    ArrayList <YourDataType> arrayList2 = new ArrayList<YourDataType>();


     int limit = 3 ; //assuming you want to copy till 3 elements.
    for(int i=0;i<limit;i++)
        arrayList2.add(arrayList1.get(i));
Kavach Chandra
  • 770
  • 1
  • 10
  • 25