使用方法Collections.copy编译器错误

问题描述 投票:1回答:1

我写了这个程序将一个列表复制到另一个列表,但是我收到了一个错误。在编译其他程序的同时,我得到了这个Collections.sort()Collections.copy()的错误。任何人都可以帮我解决这个问题吗?

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));
    }

}

我得到的错误:

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>)
java list collections java-8
1个回答
4
投票

使用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);
© www.soinside.com 2019 - 2024. All rights reserved.