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;
}

4 Answers

5
Sindbad90 On

If all you need is the same method name, something like this could work:

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

public void setAbc(String str) {
    if (this.abc == null) {
        this.abc = new ArrayList<>();
    }
    this.abc.add(str);
}

Do you want to append to this list or create a new list with just on entry? This one appends to list.

6
Antoine On

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);
}

0
Borislav Markov On
private List<String> abc;

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

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

public void setAbc(String newItem) {
    if (this.abc == null) {
        this.abc = new java.util.ArrayList<>();
    }
    this.abc.add(newItem);
}

You add a new method and append to the list. As mentioned from ItFreak this is called overloading.

0
Hanamant Malakagond On

How can you set String to List as suggested by @ItFreak overload method for String.. Untill unless it will not work