简体   繁体   English

清空清单 <String> 在for循环的开始

[英]Empty the List<String> at the beginning of for loop

I have a for loop and it has a List, I want to make it empty every time the for loop starts. 我有一个for循环,它有一个List,我想在每次for循环启动时将其清空。

I have this globally, 我在全球都有

List<String> topDescription = new ArrayList<String>();

This is the for loop, 这是for循环,

  for (int j = 0; j < subMenuArray.length(); j++) {
            JSONObject subMenuObject = subMenuArray
                    .getJSONObject(j);

            if ((subMenuObject.getString("Description"))
                    .equals(sizeSelectedItem)) {

                //empty the topDescription here

                JSONArray extraItemEntityArray = subMenuObject
                        .getJSONArray("ExtraItemEntity");

                for (int k = 0; k < extraItemEntityArray.length(); k++) {
                    JSONObject objectE = extraItemEntityArray
                            .getJSONObject(k);
                    if ((objectE.getString("Description")) != null
                            && (objectE.getString("Type"))
                                    .equals("E")) {

                        topDescription.add(objectE
                                .getString("Description"));

                    }

                }
                break;
            }

        }

Following is the code, but I'm not sure what you are looking for coz, every iteration it makes the list empty. 以下是代码,但是我不确定您在寻找什么coz,每次迭代都会使列表为空。

You can do this in two ways, one is just clearing and other is assigning new arraylist, 您可以通过两种方式进行操作,一种是清除操作,另一种是分配新的数组列表,

topDescription.clear();

or 要么

topDescription = new ArrayList<Integer>();

为什么不进行新引用,将旧对象留给垃圾收集器?:

topDescription = new ArrayList<String>();

Instead of creating new reference, clearing the existing List is good. 代替创建新引用,清除现有列表是一件好事。 It reuses the already existing reference in the java heap but clearing the contents present in the list which makes the list to reuse with additonal overhead to JVM. 它重用了Java堆中已经存在的引用,但清除了列表中存在的内容,这使列表可以重用,并给JVM带来了额外的开销。

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

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