简体   繁体   English

接受java中ArrayList中的String作为ReturnType

[英]To accept a String in an ArrayList in java as ReturnType

I have a variable in class XYZ named abc. 我在类XYZ中有一个名为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. 该变量的返回类型是List,但早期它的返回类型是String.So,现在当一个列表作为输入时它被处理但是当一个String来时它会抛出异常。 the need is to make it compatible for both datatypes List as well as String. 需要使它兼容数据类型List和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 . 您正在寻找的概念是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所提到的,这称为重载。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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