To accept a String in an ArrayList in java as ReturnType

ank*_*r43 5 java string arraylist

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;
}
Run Code Online (Sandbox Code Playgroud)

ave*_*ler 6

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

Run Code Online (Sandbox Code Playgroud)

  • 另一方面,@ Abrikot,使`getAbc()`返回一个不可变列表,并具有不同的方法`setAbc()`,`addToAbc()`,removeFromAbc()等可能是一件好事。例如https://refactoring.guru/encapsulate-collection (4认同)
  • 使用`Collections.singletonList`时要小心。由于其不可更改性,您将无法在此列表中添加任何元素。因此`object.getAbc()。add(“ def”);`会引发错误。根据OP的需求,最好将其包装在数组列表中。 (3认同)

小智 5

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);
}
Run Code Online (Sandbox Code Playgroud)

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