Reputation: 43
I am currently learning about arrays and the weblesson from my class is teaching me about the ArrayList class. I tried to make my own array to try it out, but when I followed the format the weblesson showed me, I get a compiler error that reads: "no suitable method found for add(java.lang.String)". While highlighting the ".add".
import java.util.ArrayList;
public class String
{
ArrayList <String> myArrayList;
public void arrayTest()
{
ArrayList <String> names = new ArrayList <String> ();
names.add("John");
names.add("Smith");
names.add("Matt");
System.out.println(myArrayList.get(1));
}
}
Upvotes: 0
Views: 226
Reputation: 159754
Your class is hiding java.lang.String
so there is a type mismatch between the argument used for the add
method and your custom String
class. Rename it to something else other than String
Upvotes: 3
Reputation: 3377
Because you are naming your class String, the String in
ArrayList < String > names
is referring to your self-defined class type. Therefore, only the 'String' objects that you defined can be added to the ArrayList, not the actual Java Strings. To correct this, name your class something else.
Upvotes: 0
Reputation: 34146
What happens is that you are naming your class as String
, which will make the compiler get confused because there already exist a built-in String
.
What can you do?
Rename your class, to something different:
public class StringTest
Or use the fully qualified class name (which I wouldn't recommend):
ArrayList <java.lang.String> names = new ArrayList <java.lang.String> ();
Upvotes: 1
Reputation: 7863
The problem might be that your class is also called String
. I'm guessing the generic type of your ArrayList
is that and not the Java String
.
Upvotes: 1