【问题标题】:getting the missing numbers in array list获取数组列表中缺少的数字
【发布时间】:2019-05-28 13:00:40
【问题描述】:

我需要获取一个数组列表的缺失数字,数组列表从firebase数据库中获取它的数字,所以我需要获取不在数组中的缺失数字。 数字在 1-10 之间,并且 arrayList 包含 [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);
        }

【问题讨论】:

  • 有什么问题?你的代码不起作用吗?
  • 它将 1-10 的数字重复四次 @Carcigenicate
  • 以什么方式丢失?您还缺少 100、12345 和 Integer.MAX_VALUE,这仅是 40 亿多个缺失值中的几个。
  • @AndyTurner ,数字在 1-10 之间,数组列表包含 [3,9,7,5],打印数组中缺失的数字
  • @ReemH.Alzoubi 请edit您的问题包括相关细节。

标签: java android arraylist firebase-realtime-database


【解决方案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

【讨论】:

    猜你喜欢
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2019-10-15
    • 1970-01-01
    相关资源
    最近更新 更多