2

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.

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
Rathishkumar
  • 109
  • 10

3 Answers3

3

Collections can be converted to arrays:

UserData[] userArray = userList.toArray(new UserData[userList.size()])
Ted Cassirer
  • 364
  • 1
  • 10
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])
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
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