不兼容的类型:Int无法转换为“ class”数据类型

时间:2020-06-13 05:50:25

标签: java

我试图使用循环将值插入List,但是此列表数据类型是其中具有构造函数的类。 这是我的代码:

List<Edge> edge= Arrays.asList();
    for(int i=0;i<M;i++){
        System.out.println("insert first vertex that connected to edge : ");
        x=key.nextInt();
        System.out.println("insert second vertex that connected to edge : ");
        y=key.nextInt();
        edge.add(x,y);
    }

edge.add(x,y)行的错误消息显示:

Incompatible data types : int cannot be converted to Edge

这是边缘类:

public class Edge{
    int source, destination;
    public Edge(int source, int destination){
        this.source=source;
        this.destination=destination;
    }
}

我应该改变什么?谢谢。

2 个答案:

答案 0 :(得分:1)

edge.add(x,y)更改为edge.add(new Edge(x,y))应该会有所帮助。列表edge期望类Edge的对象,同时传递两个整数,从而导致错误。

答案 1 :(得分:0)

edge是指边的列表。

所以edge.add(__n)意味着添加一个新 边缘__n中的边缘edge

您需要这样做:

Edge new_edge = new Egde (x, y)
edge.add (new_edge)

另外,最好将列表重命名为类似 edge_listedges