如何使用集合添加列表(字符串数组)和arrayList?

时间:2015-04-04 00:02:57

标签: java list arraylist collections

我正在尝试将一个字符串数组添加到arrayList中。以下是代码:

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Arrays;

class AddAll{
    public static void main(String[] args){
        String[] words = {"apples","beef","corn","ham"};
        List<String> list = Arrays.asList(words);

        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("Youtube");
        arrayList.add("Google");
        arrayList.add("Facebook");

        for(String x : arrayList){
        System.out.printf("%s ",x);
        }
        System.out.println();

        Collections.addAll(arrayList,list);

      for(String x : arrayList){
        System.out.printf("%s ",x);
    }
  }
 }

但是,在编译期间,它会抛出错误。我无法弄清楚如何解决它?有人可以帮我这个代码吗?

  AddAll.java:21: error: method addAll in class Collections cannot be applied to           given types;
    Collections.addAll(arrayList,list);
               ^
  required: Collection<? super T>,T[]
   found: ArrayList<String>,List<String>
  reason: inferred type does not conform to upper bound(s)
  inferred: List<String>
   upper bound(s): String,Object
   where T is a type-variable:
    T extends Object declared in method <T>addAll(Collection<? super T>,T...)

1错误

1 个答案:

答案 0 :(得分:1)

Collections类中没有接受ListCollection类型的两个参数的方法。

List#add(Collection)可以执行您提出的问题

arrayList.addAll(list);