Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ArrayList扩展中的强制转换对象看不到其方法_Java_Oop_Arraylist - Fatal编程技术网

Java ArrayList扩展中的强制转换对象看不到其方法

Java ArrayList扩展中的强制转换对象看不到其方法,java,oop,arraylist,Java,Oop,Arraylist,所以我有一个有趣的问题。。。 我想访问通过ArrayList扩展从列表中检索的对象的方法 看起来是这样的: import java.util.ArrayList; import java.util.Collection; public class PropertyList<Property> extends ArrayList { private static final long serialVersionUID = -7854888805136619636L; Pr

所以我有一个有趣的问题。。。 我想访问通过ArrayList扩展从列表中检索的对象的方法

看起来是这样的:

import java.util.ArrayList;
import java.util.Collection;

public class PropertyList<Property> extends ArrayList {

private static final long serialVersionUID = -7854888805136619636L;

    PropertyList(){
        super();
    }

    PropertyList(Collection<Property> c){
        super(c);
    }

    boolean containsProperty(PropertyList<Property> pl){
        Property asdf = (Property) this.get(4);
        System.out.println(asdf.<can't access "Property" methods>);  //mark
        return false;
    }

}

您应该重构代码以显式引用属性类,而不是将其用作类似于E、T或任何其他GenericType的泛型类型。您案例中的问题是,属性被推断为GenericType,并且没有引用您的具体属性类,而是对其进行了隐藏—使其与您使用的属性相同

public class PropertyList<T> extends ArrayList<T>
但随后您将获得与现在完全相同的行为—这意味着没有方法查找/可用性,因为T可以是任何东西,并且我认为默认/推断为Object

第一种方法应该在标记行中显示getName方法

真正的问题解决者是:

PropertyList<T extends Property> extends ArrayList<T>

它实际上使用了泛型类型T来扩展属性类,而不是像在初始解决方案/尝试中那样对其进行阴影处理。

是否应该扩展ArrayList?不管怎样,你不能同时显示属性的代码吗?@Shark。就目前而言,这毫无意义。然而,显式强制转换到属性使我也想看到定义:在任何情况下,您的类声明不应该是这样的:public class PropertyList扩展了ArrayList,您可以轻松地硬编码t到属性?您没有强制转换到class属性。您将强制转换为PropertyList类的泛型类型,您选择将Property命名为Property,而不是T或E或任何其他常规的单个字母,从而隐藏Property类。您几乎不应该扩展集合类。当然不是在这种情况下。好的,然后试着像@JBNizet指出的那样使用泛型类型声明我所说的,它被隐藏了。我猜在这种情况下,属性的工作方式类似于泛型类型,类似于T或E或GenericType,它可以是任何东西,而不是具体的属性类。回答得好。如果可以的话,对于后一部分,泛型T可以限制为这样的属性:PropertyList扩展ArrayList以保留任何属性子类型的行为。这有时很有帮助!那很容易…谢谢!我不知道你可以用这样的泛型进行扩展
import java.util.ArrayList;
import java.util.Collection;

public class PropertyList extends ArrayList<Property> {

private static final long serialVersionUID = -7854888805136619636L;

    PropertyList(){
        super();
    }

    PropertyList(Collection<Property> c){
        super(c);
    }

    boolean containsProperty(PropertyList<Property> pl){
        Property asdf = (Property) this.get(4);
        System.out.println(asdf.<can't access "Property" methods>);  //mark
        return false;
    }

}
PropertyList<T> extends ArrayList<T>
PropertyList<T extends Property> extends ArrayList<T>