转换数组列表在Java中 [英] Converting array to list in Java

查看:140
本文介绍了转换数组列表在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换数组列表中的Java?

我用 Arrays.asList()但行为(和签名)从Java SE <某种程度上改变了href=\"http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-142docs-2045554.html\">1.4.2 (文档现在档案),以 1.5 0.0 和我在网上找到最片段使用1.4.2行为。

例如:

  INT [] =垃圾邮件的新INT [] {1,2,3};
Arrays.asList(垃圾邮件)


  • 在1.4.2返回一个包含元素1,2,3
  • 列表
  • 在1.5.0返回一个包含数组垃圾邮件列表

在许多情况下,它应该是很容易检测的,但有时也可以滑忽视

  Assert.assertTrue(Arrays.asList(垃圾邮件).indexOf(4)== -1);


解决方案

在你的榜样,那是因为你不能有一个原始类型的List。换句话说,列表与LT; INT&GT; 是不可能的。你可以,不过,有一个列表与LT;整数方式&gt;

 整数[] =垃圾邮件新的整数[] {1,2,3};
Arrays.asList(垃圾邮件);

这是按预期工作。

How do I convert an array to a list in Java?

I used the Arrays.asList() but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 1.5.0 and most snippets I found on the web use the 1.4.2 behaviour.

For example:

int[] spam = new int[] { 1, 2, 3 };
Arrays.asList(spam)

  • on 1.4.2 returns a list containing the elements 1, 2, 3
  • on 1.5.0 returns a list containing the array spam

In many cases it should be easy to detect, but sometimes it can slip unnoticed:

Assert.assertTrue(Arrays.asList(spam).indexOf(4) == -1);

解决方案

In your example, it is because you can't have a List of a primitive type. In other words, List<int> is not possible. You can, however, have a List<Integer>.

Integer[] spam = new Integer[] { 1, 2, 3 };
Arrays.asList(spam);

That works as expected.

这篇关于转换数组列表在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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