如何与申报值一个ArrayList? [英] How to declare an ArrayList with values?

查看:87
本文介绍了如何与申报值一个ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ArrayList中声明的Java 质疑,并回答了如何声明一个空的的ArrayList 但我怎么声明一个ArrayList与价值?

我试过以下,但它返回一个语法错误:

 进口java.io.IOException异常;
进口的java.util.ArrayList;公共类的测试{
    公共静态无效的主要(字串[] args)抛出IOException
        ArrayList的<串GT; X =新的ArrayList<串GT;();
        X = ['某某','ABC'];
    }
}


解决方案

您可以使用接受<一个构造函数创建一个新对象href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html\"><$c$c>Collection:

 列表&LT;串GT; X =新的ArrayList&LT;&GT;(Arrays.asList(XYZ,ABC));


当你有一个像这个问题,你应该访问文档,看看有什么可以构造有:


  • <一个href=\"http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList--\"><$c$c>ArrayList()


      

    构造一个具有十一个初始容量的空列表。



  • <一个href=\"http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection-\"><$c$c>ArrayList(Collection<?扩展E&GT; C)


      

    构造一个包含指定集合中的元素的列表,它们的顺序依次通过集合的迭代器返回。



  • <一个href=\"http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-int-\"><$c$c>ArrayList(int参数:initialCapacity)


      

    用指定初始容量的空列表。




使用Java的解决方案,8 <一个href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html\"><$c$c>Stream:

  Stream.of(XYZ,ABC)收集(Collectors.toList());

ArrayList declaration Java has questioned and answered how to declare an empty ArrayList but how do I declare an arraylist with values?

I've tried the following but it returns a syntax error:

import java.io.IOException;
import java.util.ArrayList;

public class test{
    public static void main(String[] args) throws IOException {
        ArrayList<String> x = new ArrayList<String>();
        x = ['xyz', 'abc'];
    }
}

解决方案

You can create a new object using the constructor that accepts a Collection:

List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));


When you have question like this, you should visit the docs and see what constructors available there:


Java 8 solution using Stream:

Stream.of("xyz", "abc").collect(Collectors.toList());

这篇关于如何与申报值一个ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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