我需要获取数组列表的缺失数字,数组列表从firebase数据库获取其数字,因此我需要获取不在数组中的缺失数字。 数字介于1到10之间,arrayList contains [3,9,7,5],因此它将在列表视图中显示“ 1 2 4 6 8 10”。 我的代码仅将1-10的数字重复四次,每个数字四次。所以我该如何在android中做到这一点。 ...这是我的代码
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ArrayList<String> array = new ArrayList<>();
ArrayList<Integer> arrayList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
students = ds.getValue(Students.class);
studentSeatNum = students.getSeatnum();
arrayList.add(Integer.valueOf(studentSeatNum));// save numbers from fire-base database into array list
}
// get missing values of the array list
for (int i = 1; i <= 10; i++) {
for (int j = 0; j < arrayList.size(); j++) {
if (i != arrayList.indexOf(j)) {
array.add(String.valueOf(i));
}
}
}
adapter = new ArrayAdapter<String>(EmptySeats.this, android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
}
答案 0 :(得分:1)
如果列表将总是在 1-10 之间的数字,例如:[3,7,9]
,请使用简单的for循环,如下所示:>
for (int i = 1; i <= 10; i++){
if (!list.contains(i)){
otherlist.add(i);
}
}
otherlist
将包含[1,2,4,5,6,8,10]
.contains()
方法检查列表是否已经有某个数字,如果没有,您只需添加该数字(在示例情况下为 i -循环的索引),移至otherlist
。