3

I have a List<User> userList need to convert to UserData[]

for(int i = 0; i < userList.size(); i++){
    userData[i] = userList.get(i);
}

It always returns null though the list size is 1. can anyone help on this.

11
  • Place the complete code Commented Jun 1, 2017 at 13:49
  • 1
    Maybe your list contains null? Also, show us the declarations and initializations of userData[] and userList, please. Commented Jun 1, 2017 at 13:49
  • show the return statement Commented Jun 1, 2017 at 13:50
  • 1
    “It always returns null” What, exactly, returns null? Nothing in the code you’ve shown can “return” anything. Commented Jun 1, 2017 at 13:56
  • 1
    Are there really two different classes? User and user data? Commented Jun 1, 2017 at 13:56

3 Answers 3

3

Collections can be converted to arrays:

UserData[] userArray = userList.toArray(new UserData[userList.size()])
Sign up to request clarification or add additional context in comments.

5 Comments

won't work. toArray returns Object[]
Correct, sorry about that
Would work, but new UserData[0] is faster. Apart from that, it's userList.size()
@ChandlerBing i tried with your solution i get ArrayIndexOutof BoundException error
this solved the issue i directly added to the setters so i accept this answer
3

just another option, this time using the power of java8 streams:

List<Foo> myList = Arrays.asList(new Foo(), new Foo(), new Foo(), new Foo());
Foo[] stringArray = myList.stream().toArray(Foo[]::new);

Edit:

Stream is actually not necessary so you can still do:

Foo[] fooArray = myList.toArray(new Foo[0])

1 Comment

not really necessary to use a stream here. Foo[] fooArray = myList.toArray(new Foo[0]);
0

Here is the code try this

import java.util.ArrayList;

public class ArrayListTest {

static UserData[] userdata = new UserData[3];

public static void main(String[] args) {
    ArrayListTest alt = new ArrayListTest();
    ArrayList<UserData> users = alt.arrayTest();

    for (int i = 0; i < users.size(); i++) {
        userdata[i] = users.get(i);
    }

    for (UserData ud : userdata) {
        System.out.println("User Name " + ud.getName());

    }

}

private ArrayList<UserData> arrayTest() {
    ArrayList<UserData> userList = new ArrayList<>();
    userList.add(new UserData("user 1"));
    userList.add(new UserData("user 2"));
    userList.add(new UserData("user 3"));
    return userList;
}

private class UserData {

    private final String name;

    public UserData(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

}

}

this is the output screen

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.