Из исходного кода:
for (int j = 3; j < digits.size(); j++) {
copy.remove(0);
copy.add(digits.get(j));
int next = arrayproduct(copy);
System.out.println("-->" + next);
System.out.println("-->" + copy);
if (next > maxproduct) {
maxproduct = next;
result = copy;
System.out.println("result-->" + result);
}
}
Переменная copy и result являются ссылками на объекты, такими как указатель на C.
Таким образом, вам нужно явно копировать (клонировать) все содержимое копии в результирующий объект каждый раз, когда изменяется значение maxproduct. Есть несколько способов достичь этого метода.
Использование метода клонирования - один простой способ сделать это;
result = copy;
до
result = (ArrayList<Integer>)copy.clone();
Итак, метод func выглядит следующим образом:
@SuppressWarnings("unchecked")
ArrayList<Integer> func() {
ArrayList<Integer> three = new ArrayList<>();
ArrayList<Integer> result = new ArrayList<>();
// array of the first 3 digits of the number
for (int index = 0; index < 3; index++) {
three.add(digits.get(index));
}
// initially the max product is the first 3 digits
int maxproduct = arrayproduct(three);
System.out.println(three); // from test [1,9,8]
System.out.println(maxproduct);// from test 72
ArrayList<Integer> copy = three;
for (int j = 3; j < digits.size(); j++) {
copy.remove(0);
copy.add(digits.get(j));
int next = arrayproduct(copy);
System.out.println(copy);
if (next > maxproduct) {
maxproduct = next;
result = (ArrayList<Integer>)copy.clone();
}
}
System.out.println(maxproduct); // returns 280 which is correct
System.out.println(result); // returns [7,5,6]
return result;
}
Тогда выходное сообщение может быть тем, что вы ожидали.
[1, 9, 8]
72
[9, 8, 3]
[8, 3, 4]
[3, 4, 8]
[4, 8, 7]
[8, 7, 5]
[7, 5, 6]
280
[8, 7, 5]
Хорошего кодирования ...