Adding multiple BigInteger values to an ArrayList

This question already has an answer here:

  • Initialization of an ArrayList in one line 32 answers

  • I'm not really sure what you're after. You have four alternatives:

    1. Add items individually

    Instantiate a concrete List type and then call add() for each item:

    List<BigInteger> list = new ArrayList<BigInteger>();
    list.add(new BigInteger("12345"));
    list.add(new BigInteger("23456"));
    

    2. Subclass a concrete List type (double brace initialization)

    Some might suggest double brace initialization like this:

    List<BigInteger> list = new ArrayList<BigInteger>() {{
      add(new BigInteger("12345"));
      add(new BigInteger("23456"));
    }};
    

    I recommend not doing this. What you're actually doing here is subclassing ArrayList , which (imho) is not a good idea. That sort of thing can break Comparator s, equals() methods and so on.

    3. Using Arrays.asList()

    Another approach:

    List<BigInteger> list = new ArrayList<BigInteger>(Arrays.asList(
      new BigInteger("12345"),
      new BigInteger("23456")
    ));
    

    or, if you don't need an ArrayList , simply as:

    List<BigInteger> list = Arrays.asList(
      new BigInteger("12345"),
      new BigInteger("23456")
    );
    

    I prefer one of the above two methods.

    4. Collection literals (Java 7+)

    Assuming Collection literals go ahead in Java 7, you will be able to do this:

    List<BigInteger> list = [new BigInteger("12345"), new BigInteger("23456")];
    

    As it currently stands, I don't believe this feature has been confirmed yet.

    That's it. Those are your choices. Pick one.


    BigIntegerArrays.asList(1, 2, 3, 4);
    

    Where BigIntegerArrays is a custom class which does what you need it to do. This helps if you are doing this often. No rocket science here - ArrayList BigIntegerArrays.asList(Integer... args) will use a FOR loop.


    Arrays.asList(new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4"));
    

    您可能可以创建一个方法,该方法返回给定一个String的新BigInteger,称之为bi(..)以减小该行的大小。

    链接地址: http://www.djcxy.com/p/27710.html

    上一篇: 初始化ArrayList

    下一篇: 将多个BigInteger值添加到ArrayList