Home > Mobile >  How to input values into the list
How to input values into the list

Time:10-23

I would like to input the string 1,2,3,hi,bye into the list.Is there anything which is missing?

public class Ex1{
public static void ques1 () {

        Example1 example1=new Example1();
         example1.test("1", "2", "3", "hi", "bye"); ****Here Is the error LINE***
    }
class Example1{
public static String test(List<String> anything){
int a=0;
List<String> ign =new ArrayList<String>();
.
.
.
return null
}
}

The error says that it is not applicable for the arguments (String,String,String,String,String)

CodePudding user response:

Try this.

class Example1 {
    public static List<String> test(String... anything){
        return List.of(anything);
    }
}

and

List<String> list = Example1.test("1", "2", "3", "hi", "bye");
System.out.println(list);

output:

[1, 2, 3, hi, bye]

CodePudding user response:

I'm not entirely certain what your question is, but given the method signature public static String test(List<String> anything), it seems that you want to return a String from a List of Strings. In that case:

import java.util.Arrays;
import java.util.List;

public class ListExample {

    public static String test(List<String> input) {
        String result = "";
        for(int i = 0; i < input.size() - 1; i  ) {
            result  = input.get(i)   ", ";
        }
        result  = input.get(input.size() - 1);
        return result;
    }    

    public static void main(String[] args) {

        List<String> list = Arrays.asList("1", "2", "3", "hi", "bye");

        System.out.println(test(list));
    }
}

If, however, as your question also suggests, you want to put a series of Strings into a List, you can simply use the first line in the main method, above, i.e.:

List<String> list = Arrays.asList("1", "2", "3", "hi", "bye");

In that case, you will still need the following import:

import java.util.Arrays;

Hope that helps!

  • Related