繁体   English   中英

变量需要声明为 final 但也需要声明为 non-final

[英]Variable needs to be declared as final but it needs to be declared as non-final too

我有一个案例,我的变量需要作为最终变量访问,但它也需要作为非最终变量。

这是我的代码:

public class ShowViewModel extends ViewModel {
    public void setShows(final String type, boolean isFavorite, FavoriteHelper favoriteHelper) {
        AsyncHttpClient client = new AsyncHttpClient();
        ArrayList<Show> listItems = new ArrayList<>();
        listItems.clear();

        if (isFavorite) {
            Cursor cursor = favoriteHelper.queryAll(type);

            // this assignment needs listItems as a non-final variable
            listItems = MappingHelper.mapCursorToArrayList(cursor);
        } else {
            String url = String.format("http://api.dev");

            client.get(url, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    try {
                        String result = new String(responseBody);
                        JSONObject responseObject = new JSONObject(result);
                        JSONArray results = responseObject.getJSONArray("results");

                        for (int i = 0; i < results.length(); i++) {
                            JSONObject shows = results.getJSONObject(i);
                            Show show = new Show();
                            show.setImage(shows.getString("poster_path"));
                            ....
                            // this assignment needs listItems as a final variable
                            listItems.add(show);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

然后,我尝试将 listItems 作为 class 的属性移动

public calss ShowViewModel extends ViewModel {
    private ArrayList<Show> listItems = new ArrayList<>();
    public void setShows(final String type, boolean isFavorite, FavoriteHelper favoriteHelper) {
        ...
    }
}

它没有显示任何错误并且运行良好。 但这会影响我申请的另一部分。

有什么解决办法吗? 谢谢你。

正常的解决方案是使用两个变量。 例如:

int i = 0;
while (i < 10) {
   i++;
   executor.submit(new Runnable() {
           public void run() {
                System.out.println(i);  // Compilation Error
           });
}

变成:

int i = 0;
while (i < 10) {
   i++;
   final int ii = i;
   executor.submit(new Runnable() {
           public void run() {
                 System.out.println(ii); // OK
           });
}

您应该能够在您的代码中使用这种方法。

这是一个简单的解决方案:

List<Show> cursorList = MappingHelper.mapCursorToArrayList(cursor);
listItems.addAll(cursorList);

暂无
暂无

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

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