Home > Software engineering >  POJO How to set value for the List
POJO How to set value for the List

Time:06-18

I want to set something like this in my Object

"citizenships": ["IN"]

It is possible that I would need set more than one citizenships e.g. ["IN","FR"] I have class

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.List;

@Getter
@Setter
@ToString
public class Citizenships {

    private List<Citizenship> citizenships = null;

    private class Citizenship {
    }
}  ```

My object is like that
public class StudentPersonalData {

private String name;
private String surname;
private String birthYear;
private String gender;
private List<String> citizenships;} ```

I have StudentPersonalData st1 = new StudentPersonalData(); I want to use something like st1.setCitizenships(.....);

How can I fill setCitizenships (....)?

CodePudding user response:

If I understand your question correctly, you want to be able to call setCitizenships with any number of arguments.

i.e. you want to be able to call st1.setCitizenships("IN") and st1.setCitizenships("IN", "FR");

Solution:

Use varargs in your function's parameters.

// StudentPersonalData.java

public void setCitizenships(String... citizenshipsArr) {
    // Add every element in citizenshipsArr into your list
    for (String citizenship : citizenshipsArr) {
        citizenships.add(citizenship);
    }
}

This lets you call setCitizenships with 0 or more arguments of type String.

Note: Inside your function, citizenshipsArr can be used as if it was a String[].

To better understand varargs, I'd recommend you to read this article: https://www.geeksforgeeks.org/variable-arguments-varargs-in-java/

CodePudding user response:

I am not sure about your structure, as you have a class of citizenships on top, but you use a List of strings later.

Maybe the following code will help you

st1.setCitizenships(List.of("IN","FR"));
  • Related