Darshaa
Darshaa

Reputation: 25

add into array object change same value java

After adding userdetails to arr array, all the elements change into same value. Please explain how to do it.

@Autowired UserDto userDto;

public ArrayList getAllUsers()  throws commonException  {
        ArrayList<UserDto> arr = new ArrayList<>(); 
        Iterable<User> user = userRepository.findAll();
        for(User userDetails: user){
             userDto.setUsername(userDetails.getUsername());
              userDto.setEmail(userDetails.getEmail());
              userDto.setPassword(userDetails.getPassword());
              arr.add(userDto);
        }



        return arr;

Upvotes: 0

Views: 124

Answers (3)

Mouad EL Fakir
Mouad EL Fakir

Reputation: 3749

You need to instantiate UserDto first :

for(User userDetails: user){

    //You need to add this
    UserDto userDto = new UserDto();

    userDto.setUsername(userDetails.getUsername());
    userDto.setEmail(userDetails.getEmail());
    userDto.setPassword(userDetails.getPassword());

    arr.add(userDto);
}

Upvotes: 0

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

you need to create a new object every time so add this in the loop.

UserDto userDto = new UserDto();

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

Your code appears to be incomplete, because you never actually declare the variable userDto nor is it initialized. However, I suspect that the solution to your problem would be to make sure that you initialize a new UserDto POJO for each iteration of the loop. Something like this:

for (User userDetails: user) {
    UserDto userDto = new UserDto();     // CRITICAL
    userDto.setUsername(userDetails.getUsername());
    userDto.setEmail(userDetails.getEmail());
    userDto.setPassword(userDetails.getPassword());

    arr.add(userDto);
}

The reason you end up with multiple copies of the same user currently is that you were reusing the same UserDto object, merely changing its values during each iteration.

Upvotes: 1

Related Questions