1

I added Strings "Hello", "Cat", "Dog" into the arraylist called values passed it to the method doubleIt() which should return a list of everything doubled, i.e.

"Hello", "Hello", "Cat", "Cat", "Dog", "Dog"

But all Im getting is []. What could I do wrong here ?

import java.util.*;

public class Addition
{

    public static void main(String [] args)
    {
        List<String> values = new ArrayList<String>();
        values.add("Hello");
        values.add("Cat");
        values.add("Dog");

        values = doubleIt(values);
        System.out.println(values);

    }

    public static List<String> doubleIt(List<String> values)
    {
        List<String> temp = new ArrayList<>();

        for(int i = 0; i < temp.size(); i++)
        {
            temp.add(values.get(i*2));
        }
        return temp;
    }
}
3
  • instead of temp.add(values.get(i*2)); you should use temp.add(values.get(i));temp.add(values.get(i)); and temp.size() replace with values.size() Commented Apr 9, 2015 at 3:17
  • What is the size of temp when you start looping? Commented Apr 9, 2015 at 3:17
  • 2
    Or simply temp.addAll(values); twice... Commented Apr 9, 2015 at 3:17

3 Answers 3

2

Your first mistake is here...

for(int i = 0; i < temp.size(); i++)

temp.size() will be 0 when it's called the first time, you really should be using a values, but this will cause an IndexOutOfBoundsException

So you could use something like...

for (int i = 0; i < values.size(); i++) {
    temp.add(values.get(i));
    temp.add(values.get(i));
}

instead

Sign up to request clarification or add additional context in comments.

Comments

1

First change your for loop condition from

for(int i = 0; i < temp.size(); i++)

to

for(int i = 0; i < values.size(); i++)

and then add values 2 times each.

Comments

1

Your for loop in doubleIt() was looping up to the wrong list size. And you were trying to multiply a string by 2, instead of adding it twice.

public static List<String> doubleIt(List<String> values)
{
    List<String> temp = new ArrayList<>();

    for(int i = 0; i < values.size(); i++) // <-- you needed to loop up to the size of the values list, not the temp list
    {
        temp.add(values.get(i));
        temp.add(values.get(i));
    }
    return temp;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.