E
E
Eban2019-10-03 11:56:59
Java
Eban, 2019-10-03 11:56:59

Can't return an array from a method?

Explain how to return an array from the method, I substitute anything in most cases, it writes cannot convert from String to String[]
the task sounds like this: In the UserRepository class, write the method:
getUserNames() - to get an array of usernames,
the code:

<b>public class User</b> {
  private String name;

        public User(String name) {
    this.name = name;

        public String getName() {
    return name;
  }

<b>public class UserRepository</b>{
          User[] users;

         public UserRepository(User[] users) {
    this.users = users;
  }
  
  public User[] getUsers() {
    return users;
  }
  
  public String[] getUserNames() {
    for(User user: users) {
      user.getName();
    } // здесь нужно вернуть все имена юзеров - массив помогите!!!
    return user.getName; // пробовал return users; User.Name; (String[]) user.getName
    
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2019-10-03
@Eban

public String[] getUserNames() {
            return Stream.of(users).map(User::getName).toArray(String[]::new);
        }

Ps: it's better to use List instead of array

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question