【问题标题】:Compile error while converting array to Set in java在java中将数组转换为Set时编译错误
【发布时间】:2014-09-24 09:37:48
【问题描述】:

我试图将 int 数组转换为 Set<Integer>

int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));

但是编译器不接受上面的代码。它说:“构造函数 HashSet(List) 未定义。”好吧,我认为 int 应该自动装箱。

我稍微修改了代码,把int改成String

String[] arr = {"hello", "world"};
Set<String> s = new HashSet<String>(Arrays.asList(arr));

此代码可以正常工作。

我尝试了以下,将int更改为Integer

Integer[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));

这是通过编译。

我的问题是:为什么java编译器不接受第一个代码?

【问题讨论】:

标签: java arrays set


【解决方案1】:
int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));

因为您的SetInteger(Object) 类型,而arrayint(primitive) 类型。

阅读Arrays.asList()

Arrays.asList() // takes in put as Generics

Java 中的泛型不适用于 primitive 类型,如 int 中的类型。这就是您收到此错误的原因。

【讨论】:

  • Arrays.asList(arr) 返回Integer 的列表。集合不支持原语。
  • @sᴜʀᴇsʜᴀᴛᴛᴀ 问题不在于返回类型,问题在于asList()中的输入类型
  • @TheLostMind 问题与返回类型无关,asList() 中的输入类型问题
【解决方案2】:

您的问题是对Arrays.asList(arr) 的调用。它被原始数组的使用弄糊涂了。 Java 对待基元和对象的方式不同。

asList 只知道对象数组,在您的情况下,它将整个数组视为单个元素。也就是说,asList(arr) 正在返回 Set&lt;int[]&gt;,因此以下情况为真:

Set<int[]> s = new HashSet<Integer>(ints);

这不是你的意思。

Java 中没有原始数组的自动装箱。最快的解决方法是使用 Integer 而不是 int 作为输入数组:

Integer[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};   // java supports autoboxing when declaring an array 
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));

否则您将不得不自己迭代和添加元素。

int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>();        
for ( int v : arr ) {
    s.add(v);  // autoboxing of a single int is supported by Java, and happens here
}

【讨论】:

    【解决方案3】:

    在 java 中,容器需要“对象”,而基元不是从对象派生的。泛型允许你假装没有包装器,但你仍然要为拳击的性能付出代价。这对许多程序员来说很重要。

    列表列表;这也是为什么有原始类型的包装类的原因:

    int -> Integer
    
    boolean -> Boolean
    
    double -> Double
    
    byte -> Byte etc...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 2011-08-22
      • 2012-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多