如何在java中消除copyOf方法中的错误?
我在复制方法中遇到错误。谁能告诉我哪里错了?我犯了一个错误 错误日志:如何在java中消除copyOf方法中的错误?,java,arrays,object,Java,Arrays,Object,我在复制方法中遇到错误。谁能告诉我哪里错了?我犯了一个错误 错误日志: The method `copyOf(U[], int, Class<? extends T[]>)` in the type Arrays is not applicable for the arguments (Object[], int, Class<String>) Can only iterate over an array or an instance of `java.lang.
The method `copyOf(U[], int, Class<? extends T[]>)` in the type Arrays is not applicable for the arguments (Object[], int, Class<String>)
Can only iterate over an array or an instance of `java.lang.Iterable`
方法`copyOf(U[],int,Class是数组的第三个参数。copyOf
要求是数组。要解决您的问题,只需添加[]
String[]str=Arrays.copyOf(obj,2,String[].class);
copyOf的第三个参数是副本的类型,而不是数组元素的类型。因此它必须是数组类型。
public class createdevice {
static List<String> Mylist = new ArrayList<String>();
public static void main(String[] args) throws FileNotFoundException {
File file = new File("/home/madhu/Desktop/demo.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
String st = sc.nextLine();
Mylist.add(st);
}
Object[] obj = Mylist.toArray();
String[] str = Arrays.copyOf(obj,obj.length,String.class);
for(int i : str.length) {
System.out.println("String is "+str[i]);
}
// TODO Auto-generated method stub
}
}