Yuri
Yuri

Reputation: 99

Problems with returning ArrayList

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;
    }
}

Upvotes: 1

Views: 115

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347234

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

Upvotes: 2

Jason
Jason

Reputation: 11832

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;
}

Upvotes: 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.

Upvotes: 1

Related Questions