dimancrown dimancrown - 5 months ago 52
Java Question

List to String using toString() in java

I'm having ArrayList Contains of String. I would like to check whether the character is present in the arraylist. I'm using the following code.

if(list.toString.contains(char))
{
// enter code here
}


Can i use this toString() method. What is the drawback?

Answer Source
if(list.toString.contains(char))

String's contains() method won't take char as param, instead check with indexOf

Your code works, with little modifications.

A small example here:

     List<String> list= new ArrayList<>();
     list.add("test");
     list.add("test2");
     if (list.toString().indexOf('t') > -1)      // True
     {
         System.out.println("yes there");
     }

Note:

As a workaround, Make an char array and add your char in to that array and then use contains method.