Josh
Josh

Reputation: 163

Java wont let me call method with list

I am trying to call a method from another class with list but it is not letting me. Here is my call statement:

case 2:  pm.displayList(list);
        break;

case 3:  pm.searchList(scan, list);
        break;

And here are my methods:

public void displayList(List list){
    System.out.print(list);
}
//search for element
public void searchList(Scanner scan, List list){
    System.out.println("Search for element:\t");
    String p = scan.nextLine();

    if (list.contains(p))
        System.out.println(p + " is in the list");
    else
        System.out.println(p + " is not in the list.");
}

Here is my error:

MyProgram7.java:50: displayList(java.util.List) in Prog7Methods cannot be applied to (MyList<java.lang.String>)
            case 2:  pm.displayList(list);
                                   ^
MyProgram7.java:53: searchList(java.util.Scanner,java.util.List) in Prog7Methods cannot be applied to (java.util.Scanner,MyList<java.lang.String>)
            case 3:  pm.searchList(scan, list);

Upvotes: 0

Views: 224

Answers (4)

Steve J
Steve J

Reputation: 2674

Josh, is this a variation on your question here? Check my answer -- you want to make sure that MyList implements the List interface.

public class MyList<T> implements List<T> {
  // you will need to provide implementations for all the
  // methods that make up the List interface here in order to make it compile
}

If you are struggling with Java interfaces, there are plenty of explanations and tutorials on the Web you can look at (here is an example).

Upvotes: 0

John B
John B

Reputation: 32949

The code searchList is expecting a List<Object>, it appears you are passing a List<String>. I am assuming that MyList implements List.

Since both the method expect each element in the list to be a String, take List<String>

Upvotes: 0

NPE
NPE

Reputation: 500357

The functions expect a List, and you're supplying a MyList<java.lang.String>. Check that MyList implements the List interface (I bet it doesn't).

Also, you probably shouldn't be using the raw List type; List<String> -- or MyList<String>, as appropriate -- would be preferable.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500595

It looks like your MyList<T> class doesn't implement the List interface. Of course, you haven't shown us MyList<T>, but that's what the compiler error suggests.

(As an aside, do your methods really need to take the raw List type instead of using generics?)

Upvotes: 0

Related Questions