简体   繁体   中英

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

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

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.

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.

如何按字符串的@ItFreak重载方法的建议将String设置为List ..直到除非它不起作用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM