Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To accept a String in an ArrayList in java as ReturnType

I have a variable in class XYZ named abc. The return type of that variable is List but earlier its return type was String.So, now when a list comes as a input it is processed but when a String comes it throws Exception. the need is to make it compatible for both datatypes List as well as String. Please help

private List<String> abc;

public List<String> getAbc() {
    return abc;
}

public void setAbc(List<String> abc) {
    this.abc = abc;
}
like image 395
ankur43 Avatar asked Dec 17 '22 17:12

ankur43


1 Answers

The concept you are looking for is method overloading.

A method is defined by its name and all its parameters, so you can define two different methods like this:

public void setAbc(List<String> abc) {
    this.abc = abc;
}

public void setAbc(String abc) {
    // Collections.singletonList creates an *immutable* list
    // See: https://docs.oracle.com/javase/10/docs/api/java/util/Collections.html#singletonList(T)
    this.abc = Collections.singletonList(abc);
}

like image 97
aveuiller Avatar answered Jan 06 '23 05:01

aveuiller