Tony Hello
Tony Hello

Reputation: 69

What data type to use for a method that has a List<string> parameter in java?

public void setPersonID(List<String> personID) {
    this.personID = personID;
}

PeopleList.setPersonID();

I want to call the setPersonID() method, but I don't know what kind of data type to use for the List<String> parameter. Can you tell me what I should use?

Upvotes: 0

Views: 60

Answers (2)

eakgul
eakgul

Reputation: 3698

List<T> is an interface in Java. So you cannot instantiate it. Instead of that you might use ArrayList or LinkedListdepends your requirements(ArrayList prefferable). Then you can use the List interface as field type, not field instance.

//example

private List<String> personID = new ArrayList<String>();

or

private List<String>personID = new LinkedList<String>();

With this way you will use a list with different implementations, but doesn't care your implementation(you will be still use List methods and fields).

Then lets implement setter and getters:

private List<String> personID;

//mark methods publicity with your needing(public, private or protected)
public List<String> getPersonID(){
return this.personID;
}

public void setPersonID(List<String>personId){
this.personId = personId;
}

public static void Test(){
Person p = new Person();

p.setPersonId(new LinkedList<String>()); //you can initialize with LinkedList
p.setPersonId(new ArrayList<String>()); //you can Also initialize with ArrayList

//adding Item to PersonId
p.getPersonId().add("1234567890");

}

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Since setPersonID() receiving a list. So just create a list and pass to it.

List<String> list = new ArrayList<String>();
list.add("something"); // person id ?

That just prepares list and then you can do

PeopleList.setPersonID(list);

but it looks suspicious to me that you are passing a list to set a person id.

And before proceeding from here just spend some time here

Upvotes: 2

Related Questions