我怎么能转换List成ArrayJava中?
检查以下代码:
ArrayList<Tienda> tiendas;
List<Tienda> tiendasList;
tiendas = new ArrayList<Tienda>();
Resources res = this.getBaseContext().getResources();
XMLParser saxparser = new XMLParser(marca,res);
tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();
this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);
Run Code Online (Sandbox Code Playgroud)
我需要tiendas使用值填充数组tiendasList.
如何转换int[]成List<Integer>Java中?
当然,我对任何其他答案感兴趣,而不是逐个循环地进行.但如果没有其他答案,我会选择那个最好的,以表明这个功能不是Java的一部分.
我正在尝试使用以下代码将包含Integer对象的ArrayList转换为原始int [],但它会引发编译时错误.是否可以用Java进行转换?
List<Integer> x = new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);
Run Code Online (Sandbox Code Playgroud) 我是Java的新手,非常困惑.
我有一个长度为4的大型数据集,int[]我想计算4个整数的每个特定组合出现的次数.这与计算文档中的单词频率非常相似.
我想创建一个Map<int[], double>将每个int []映射到一个运行计数的列表迭代,但Map不采用原始类型.
所以我做了 Map<Integer[], Double>
我的数据存储为一个ArrayList<int[]>所以我的循环应该是这样的
ArrayList<int[]> data = ... // load a dataset`
Map<Integer[], Double> frequencies = new HashMap<Integer[], Double>();
for(int[] q : data) {
// **DO SOMETHING TO convert q from int[] to Integer[] so I can put it in the map
if(frequencies.containsKey(q)) {
frequencies.put(q, tfs.get(q) + p);
} else {
frequencies.put(q, p);
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定在评论中需要哪些代码才能使这项工作转换int[]为Integer[].或者我可能从根本上对正确的方法感到困惑.
我可以想到两种方式:
public static IntStream foo(List<Integer> list)
{
return list.stream().mapToInt(Integer::valueOf);
}
public static IntStream bar(List<Integer> list)
{
return list.stream().mapToInt(x -> x);
}
Run Code Online (Sandbox Code Playgroud)
什么是惯用的方式?也许已经有一个库函数完全符合我的要求?
试图解决什么应该是一个简单的问题.有一个Bytes列表,想要在函数末尾将它转换为字节数组.
final List<Byte> pdu = new ArrayList<Byte>();
....
return pdu.toArray(new byte[pdu.size()]);;
Run Code Online (Sandbox Code Playgroud)
编译器不喜欢我的语法toArray.如何解决这个问题?
有没有办法,将整数列表转换为整数数组(非整数).像List to int []之类的东西?不循环遍历列表并手动将intger转换为int.
在JUnit 4测试中,我有一个方法getValues()返回一个List<Double>我想要与引用列表进行比较的对象.到目前为止,我发现的最佳解决方案是使用org.hamcrest.collection.IsArray.hasItems和org.hamcrest.Matchers.closeTo喜欢这样:
assertThat(getValues(), hasItems(closeTo(0.2, EPSILON), closeTo(0.3, EPSILON)));
Run Code Online (Sandbox Code Playgroud)
这适用于仅返回少量值的测试.但是如果测试返回更多值,这绝对不是最好的方法.
我也尝试了以下代码.要编译的代码需要向下转换为Matcherbefore hasItems:
List<Matcher<Double>> doubleMatcherList = new ArrayList<Matcher<Double>>();
doubleMatcherList.add(closeTo(0.2, EPSILON));
doubleMatcherList.add(closeTo(0.3, EPSILON));
assertThat(getValues(), (Matcher) hasItems(doubleMatcherList));
Run Code Online (Sandbox Code Playgroud)
比较失败,我不明白为什么:
java.lang.AssertionError:Expected :(一个包含<[数字值<1.0E-6> <0.2>的数字,<1.0> -0> <0.3>的数值>]>的集合得到:<[ 0.2,0.30000000000000004]>
是否有更好的方法来比较两个大型双打名单?这里的困难是需要数值公差来验证结果getValues()是否等于我的参考列表.对于任何对象列表,这种比较似乎都很容易,但对于列表却没有Double.