Reputation: 181
I'm doing a Java practice which ask me to iterate through each number in the arraylist and for each number, insert the number plus one to the next position of the list. Return the resulting list after finished. If there is no elements in the provided list, directly throw IllegalArgumentException.
public class ListAddNPlusOne {
public static ArrayList<Integer> addNPlusOne(ArrayList<Integer> numbers)
{
if(numbers.size() == 0)
{
throw new IllegalArgumentException();
}
int result;
for (int num : numbers){
result += num;
}
}
}
This is the code I have so far. I did the throw exception and iterate through the list, I add 1 to the found integer of that list. But I don't know how to return the newest list, I'm also not sure if my thinking is right on this. Thanks for any help/ hints!
Upvotes: 0
Views: 304
Reputation: 201487
You appear to be confused as to the requirements. I can't tell why you have result
. First, I would test for null
and I would prefer isEmpty()
to .size() == 0
. Next, create new ArrayList
to store the values you want to return. Then, iterate the values in numbers
. For each num
add that to the new ArrayList
(and then add that + 1
). Finally return the new ArrayList
. Like,
public static ArrayList<Integer> addNPlusOne(ArrayList<Integer> numbers) {
if (numbers == null || numbers.isEmpty()) {
throw new IllegalArgumentException();
}
ArrayList<Integer> al = new ArrayList<>();
for (Integer num : numbers) {
al.add(num);
al.add(num + 1);
}
return al;
}
Without creating a new ArrayList
using a ListIterator
like
public static ArrayList<Integer> addNPlusOne(ArrayList<Integer> numbers) {
if (numbers == null || numbers.isEmpty()) {
throw new IllegalArgumentException();
}
ListIterator<Integer> li = numbers.listIterator();
while (li.hasNext()) {
int v = li.next();
li.add(v + 1);
}
return numbers;
}
Upvotes: 1