函数没有扩展到其他类

时间:2015-11-13 15:43:27

标签: java android

我有一个充满了吸气剂和制定者的课程,所以我可以制作一个手表列表,并让我的应用程序的其余部分可以访问它:

Watch.java:



public class Watch {

    private String brand, mvmt, serial, urlLoc;
    private int wr, year;
    private double price;
    //getters and setters

}




我想用它来获取一个列表:



package com.example.pat.watchproj;
import java.util.LinkedList;

public class WatchList extends LinkedList {
    //set up the watch list so it can be accessed through the app
    private static WatchList wlInst = new WatchList();

    public static WatchList getInstance(){
        if(wlInst == null){
            wlInst = new WatchList();
        }
        return wlInst;
    }
    private WatchList(){

    }
    public static void setInstance(WatchList watchList){
        wlInst = watchList;


    }
}




以下是我如何添加手表的示例

public void addWatch(View view){
    //initilize watch list and all edit texts
    //will need to parsedouble and parseinteger
    watchList = WatchList.getInstance();
    Watch usrWatch = new Watch();
    EditText addBrand = (EditText) findViewById(R.id.addBrand);
    EditText addSerial = (EditText) findViewById(R.id.addSerial);
    EditText addMvmt = (EditText) findViewById(R.id.addMvmt);
    EditText addWr = (EditText) findViewById(R.id.addWr);
    EditText addYear = (EditText) findViewById(R.id.addYear);
    EditText addPrice = (EditText) findViewById(R.id.addPrice);
    EditText addUrl = (EditText) findViewById(R.id.addUrl);

    //add to object now
    usrWatch.setBrand(addBrand.getText().toString());
    usrWatch.setMvmt(addMvmt.getText().toString());
    usrWatch.setSerial(addSerial.getText().toString());
    usrWatch.setWr(Integer.parseInt(addWr.getText().toString()));
    usrWatch.setPrice(Double.parseDouble(addPrice.getText().toString()));
    usrWatch.setYear(Integer.parseInt(addYear.getText().toString()));
    usrWatch.setUrlLoc(addUrl.getText().toString());

    watchList.add(usrWatch);
    WatchList.setInstance(watchList);

    Toast.makeText(addWatch.this, "Watch added", Toast.LENGTH_SHORT).show();
}

所以,在主要活动中,当我写这篇文章时:

public void onOption8 (MenuItem i){
    //show most expensive
    WatchList watchList = WatchList.getInstance();
    int x = 0;
    for(int a = 0; a < watchList.size(); a++) {
        if (watchList.get(x).getPrice() <  watchList.get(a).getPrice()) {
            x = a;

        }
    }
}

因此,在运行之后,我应该可以使用watchList.get(x).getSerial()来获取最昂贵的手表的序列。但android studio告诉我它无法解决onOption8中的方法getPrice,而且我不确定我哪里出错了。如果我不清楚/可以提供更多信息,请告诉我。感谢

2 个答案:

答案 0 :(得分:4)

您尚未为自定义LinkedList实施提供类型;因此get(x)正在返回Object。将WatchList类声明更改为:

public class WatchList extends LinkedList<Watch> {
    ...
}

答案 1 :(得分:1)

可能会发生此错误,因为您还没有为WatchList类提供类型参数。在onOption8中,编译器不知道您收到的WatchList是否为&lt;字符串&gt;,&lt; Car&gt;,或&lt;观看&gt;。

确保您只是创建一个Watch类型的LinkedList,就像这样

LinkedList<Watch> ll = new LinkedList<Watch>() 

或者您指定WatchList实际上是Watch对象的LinkedList,而不是WatchList类中的任何其他内容。