简体   繁体   English

Java不会让我用list调用方法

[英]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);

The functions expect a List , and you're supplying a MyList<java.lang.String> . 这些函数需要一个List ,而你正在提供一个MyList<java.lang.String> Check that MyList implements the List interface (I bet it doesn't). 检查MyList实现了List接口(我敢打赌它没有)。

Also, you probably shouldn't be using the raw List type; 此外,您可能不应该使用原始List类型; List<String> -- or MyList<String> , as appropriate -- would be preferable. List<String> - 或MyList<String> ,视情况而定 - 将是更可取的。

It looks like your MyList<T> class doesn't implement the List interface. 看起来你的MyList<T>类没有实现List接口。 Of course, you haven't shown us MyList<T> , but that's what the compiler error suggests. 当然,您还没有我们展示MyList<T> ,但这就是编译器错误所暗示的内容。

(As an aside, do your methods really need to take the raw List type instead of using generics?) (顺便说一句,你的方法真的需要采用原始的List类型而不是使用泛型吗?)

The code searchList is expecting a List<Object> , it appears you are passing a List<String> . 代码searchList期待List<Object> ,看起来你正在传递List<String> I am assuming that MyList implements List . 我假设MyList实现了List

Since both the method expect each element in the list to be a String , take List<String> 由于该方法都希望列表中的每个元素都是String ,因此请使用List<String>

Josh, is this a variation on your question here ? 乔什,这是你问题的一个变种吗? Check my answer -- you want to make sure that MyList implements the List interface. 检查我的答案 - 你想确保MyList实现了List接口。

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 ). 如果您正在努力使用Java接口,那么您可以在Web上查看大量的解释和教程(这是一个示例 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM