0

Как можно заполнить ArrayList сразу значениями? Например если бы был обычный тип данных, то с помощью Collections.addAll(...). По заданию надо заполнить переменные value1 и value2 так: value1 = (a, 1, 0) value2 = (b, 0, 1)

public static ArrayList<BigInteger> Euclid(BigInteger a, BigInteger b) {
    if(a.compareTo(b) > 0) {
        ArrayList<BigInteger> value1 = new ArrayList<BigInteger>();
        ArrayList<BigInteger> value2 = new ArrayList<BigInteger>();
    }
}

Как это можно сделать, 6 раз не вызывая value1.add()

1
  • В этот вопрос следует включить больше подробностей и уточнить проблему. Вопрос непонятен. 21 сен 2022 в 18:52

1 ответ 1

0

Следует использовать конструктор ArrayList<>(Collection<? extends E> collection), принимающий на вход "начальную" коллекцию, которую можно формировать несколькими способами:

  1. Arrays.asList:
import static java.util.Arrays.asList;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;

// ...

List<BigInteger> value1 = new ArrayList<>(asList(a, ONE, ZERO));
List<BigInteger> value2 = new ArrayList<>(asList(b, ZERO, ONE));
  1. List.of (Java 9+)
List<BigInteger> value1 = new ArrayList<>(List.of(a, ONE, ZERO));
List<BigInteger> value2 = new ArrayList<>(List.of(b, ZERO, ONE));

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.