java - 不兼容的类型泛型 Java

标签 java generics

我做了这段代码:

import java.util.LinkedList;

public class Node<T> {
private T data;
private LinkedList<T> children;
public Node(T data) {
    this.data = data;
    this.children = new LinkedList<T>();
}
public T getData() {
    return this.data;
}
public LinkedList<T> getChildren(){
    return this.children;
}
}


public class Graph <T> implements Network<T> {
private Node source;
private Node target;
private ArrayList<Node> nodes = new ArrayList<Node>();


public Graph(T source,T target) {
    this.source = new Node(source);
    this.target = new Node(target);


}


public T source() {
    return source.getData();
}

public T target() {
    return target.getData();
}

我在 source() 和 target() 上收到此错误:required T found java.lang.Object 为什么? getData()函数的返回类型是T(generic type of return)

最佳答案

private Node source;
private Node target;

这些应该是Node<T> .同样在以下几行中。编译器会给你一个警告。注意它。 (当您混合原始类型和泛型时,Java 语言规范通常要求编译器放弃。)

关于java - 不兼容的类型泛型 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43268768/

相关文章:

generics - 使用泛型的计算表达式

C# LINQ to SQL : Refactoring this Generic GetByID method

java - 使用反射调用外部 JAR/CLASS 上包含 Hibernate 事务的方法 (Java EE)

java - Android 应用程序在启动时崩溃,代码为 "E/dex2oat: Failed to create oat file"和 "non-0 exit status"

java - 查找周围给定经纬度的纬度值(即: location) with specified radius using java program

java - 编译应用程序使用或覆盖已弃用的 API 时出错

java - try catch null 和空数组

c# - 实现缺少新约束的通用接口(interface)

Java泛型子反向引用父级/选择子类属性

Java 通用 Csv 字符串到枚举列表