0

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));
 }
}
asked Jan 1, 2015 at 17:58
1
  • 3
    To answer your next question about NullPointerException: you created one ArrayList and stored it in names reference, then you filled it with data, but in next step you are trying to read data from uninitialized myArrayList reference. Commented Jan 1, 2015 at 18:02

4 Answers 4

3

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

answered Jan 1, 2015 at 18:00

Comments

1

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.

answered Jan 1, 2015 at 18:00

Comments

1

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> ();
    
answered Jan 1, 2015 at 18:02

Comments

0

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.

answered Jan 1, 2015 at 18:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.