user3219993
user3219993

Reputation: 25

Size error on Collections.Copy(List b,List a) in java

I want to copy a list of class to another list of class,but i have an error said that destination list size is zero but I initialed size for destination list.

public class Programs {

public Programs() {
    private int number;
    private String name;
    private int enterT;
    private int burstT;
    private int priority;
    ......
}


 public void SJF(List<Programs> progList){   
    List<Programs> tempProgListMin = new ArrayList<>(progList.size());
    Collections.copy(tempProgListMin, progList);
 }

I have error that said size of tempProgListMin is 0 and is smaller than size of progList, I think, I wrote code correctly but I don't know why it has error. I need a copy that when i change something in list b(copy one) nothing change in list A sorry for English!

Upvotes: 0

Views: 229

Answers (3)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

Consider my example

List<String> list1=new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");

List<String> list2=new ArrayList<>(list1);   

Now it works fine.

Change your code as

List<Programs> tempProgListMin = new ArrayList<>(progList);

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34166

size() return the number of elements in the list, not the inicial capacity that you passed as argument. Therefore, tempProgListMin size will be 0.

You can use this overloaded constructor:

List<Programs> tempProgListMin = new ArrayList<>(progList);

From Java Docs:

public ArrayList(Collection c): Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

Upvotes: 1

Keerthivasan
Keerthivasan

Reputation: 12890

As per docs of Collections.copy(destinationList,SourceList) method,

The destination list must be at least as long as the source list. So, your destination list size seems to be zero and lesser than the lenght of the source list

Upvotes: 0

Related Questions