如何解决当我们已经创建了ArrayList来存储JSONArray时,需要创建列表吗?
当我们已经创建了ArrayList来存储JSONArray时,创建列表的需求是什么? 这段代码是使用齐射库从JSON格式的互联网访问数据。我在理解ArrayList和List的使用时遇到了一些问题。我们不能只排除列表吗?
//What is the use of the List?
ArrayList<Question> questionArrayList= new ArrayList<>();
public List<Question> getQuestions (){
JsonArrayRequest jsonArrayRequest =new JsonArrayRequest(Request.Method.GET,url,null,new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for(int i=0;i<response.length();i++){
Question question = new Question();
try {
question.setQuestionId(response.getJSONArray(i).getString(0));
question.setTorF(response.getJSONArray(i).getBoolean(0));
questionArrayList.add(question);//If we had to add the question entries to the questionArrayList then why create a list(getQuestions)?
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
};
//我的问题类是这样的:-
打包com.example.trivia.model;
公共课问题{
private String QuestionId;
private boolean IsTorF;
public Question(String questionId,boolean isTorF) {
this.QuestionId = questionId;
this.IsTorF = isTorF;
}
public Question(){
}
public String getQuestionId() {
return QuestionId;
}
public void setQuestionId(String questionId) {
QuestionId = questionId;
}
public boolean isTorF() {
return IsTorF;
}
public void setTorF(boolean torF) {
IsTorF = torF;
}
}
解决方法
您不必选择它。
更新:
基于方法ArrayList<Question>
的返回类型,这表明封装。这对于创建API或存储库类非常普遍。在当前的实现中,我们假设您的调用类期望将数据用作ArrayList。毫不奇怪,返回类型是ArrayList。现在,在项目的后面,我们需要的数据是LinkedList。当然,您可以添加代码以使其正常工作,也可以按原样实现,将List的实现分离。
旧答案:
您应该为您的回复创建一个不可变的列表,以确保始终保持原始回复不变。在此示例中,将响应设置为不可变列表,并将每个项目添加到可变列表中,以便您可以修改内容。由于Java是传递引用,因此这也减少了稍后遍历列表并复制值的另一步骤
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。