Himanshu Joshi
Himanshu Joshi

Reputation: 66

Compiler error with method Collections.copy

I wrote this program to copy one list to another, but I am getting an error. And while compiling other programs too I got error with this Collections.sort() and Collections.copy(). Can anyone help me out with this?

import java.util.*;
import java.util.ArrayList;
import java.util.Collection;

class CopyList {

    public static void main(String[] args) {

        Collection<String> srcstr = new ArrayList<String>();

        srcstr.add("New York");
        srcstr.add("Atlanta");
        srcstr.add("Dallas");
        srcstr.add("Madison");
        System.out.println("Number of elements: " + srcstr.size());
        srcstr.forEach(s->System.out.println(s));
        Collection<String> deststr = new ArrayList<String>();
        deststr.add("Delhi");
        deststr.add("Mumbai");
        Collections.copy(srcstr,deststr);
        deststr.forEach(s->System.out.println(s));
    }

}

Error I am getting:

CopyList.java:17: error: method copy in class Collections cannot be applied to given types;
                Collections.copy(srcstr,deststr);

                           ^
  required: List<? super T>,List<? extends T>

  found: Collection<String>,Collection<String>

  reason: cannot infer type-variable(s) T

    (argument mismatch; Collection<String> cannot be converted to List<? super T>)

  where T is a type-variable:

    T extends Object declared in method <T>copy(List<? super T>,List<? extends T>)

Upvotes: 1

Views: 277

Answers (1)

Mani Ratna
Mani Ratna

Reputation: 911

Change your collection list with arraylist.

List<String> srcstr = new ArrayList<String>();
srcstr.add("New York");
srcstr.add("Atlanta");
srcstr.add("Dallas");
srcstr.add("Madison");

List<String> deststr = new ArrayList<String>();
deststr.add("Delhi");
deststr.add("Mumbai");

Collections.copy(srcstr, deststr);

Upvotes: 4

Related Questions