阵列的Arrays.asList() [英] Arrays.asList() of an array

查看:128
本文介绍了阵列的Arrays.asList()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是错的这种转换?

public int getTheNumber(int[] factors) {
    ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));  
    Collections.sort(f);
    return f.get(0)*f.get(f.size()-1);
}

我读<一个找到解决办法后作出此href=\"http://stackoverflow.com/questions/157944/how-to-create-arraylist-arraylistt-from-array-t-in-java\">How在Java中从阵列(T [])创建的ArrayList(ArrayList的&LT; T&GT)。 (排序),第二行中的 getTheNumber(...)将导致以下异常:

I made this after reading the solution found in How to create ArrayList (ArrayList<T>) from array (T[]) in Java. The second line (sorting) in getTheNumber(...) causes the following exception:

异常线程mainjava.lang.ClassCastException:[我是不是可以转换为java.lang.Comparable的]

Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to java.lang.Comparable]

什么是错在这里?我也知道排序可与 Arrays.sort()来完成,我只是好奇这一点。

What is wrong here? I do realize that sorting could be done with Arrays.sort(), I'm just curious about this one.

推荐答案

让我们考虑下面的简单示例:

Let's consider the following simplified example:

public class Example {
    public static void main(String[] args) {
        int[] factors = {1, 2, 3};
        ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));
        System.out.println(f);
    }
}

在的println此行打印类似于[I @ 190d11]这意味着你实际上已经构建了一个包含一个ArrayList INT的阵列

您IDE和编译器应该警告在code未经检查的任务。你应该总是使用新的ArrayList&LT;整数GT;()新的ArrayList&LT;&GT;()而不是新的ArrayList()。如果你已经使用过它,就不会有因为试图通过一个编译错误列表&LT; INT []方式&gt; 来构造

Your IDE and compiler should warn about unchecked assignments in that code. You should always use new ArrayList<Integer>() or new ArrayList<>() instead of new ArrayList(). If you had used it, there would have been a compile error because of trying to pass List<int[]> to the constructor.

有没有从自动装箱 INT [] 整数[] ,并反正自动装箱仅在语法糖编译器,所以在这种情况下,你需要手动执行数组复制:

There is no autoboxing from int[] to Integer[], and anyways autoboxing is only syntactic sugar in the compiler, so in this case you need to do the array copy manually:

public static int getTheNumber(int[] factors) {
    List<Integer> f = new ArrayList<Integer>();
    for (int factor : factors) {
        f.add(factor); // after autoboxing the same as: f.add(Integer.valueOf(factor));
    }
    Collections.sort(f);
    return f.get(0) * f.get(f.size() - 1);
}

这篇关于阵列的Arrays.asList()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆