如何删除列表A的所有内容而不删除包含列表A的列表的内容。?

时间:2021-02-28 03:59:36

标签: java list

我在尝试清除列表并再次使用时遇到问题。

我有以下文本,它在列表中分为多个单词: “你好,这个文本是一个样本。再次你好,这是另一个文本。”

我需要做的是连接列表的元素,直到找到“文本”一词,然后将列表的索引保存在另一个列表中。然后清除列表,再次连接直到出现“文本”一词并保存新索引。我用clean()方法清理了list,但是list的list也清理了。

我的列表列表的输出是一个空列表:

Hi, this text is a sample. 
List of index: [0, 1, 2, 3]

Hello again, this is another text.
List of index: [4, 5, 6, 7, 8, 9]

List of Lists: [[], []]

我需要的是以下内容:

Hi, this text is a sample. 
List of index: [0, 1, 2, 3]

Hello again, this is another text.
List of index: [4, 5, 6, 7, 8, 9]

List of Lists: [[0, 1, 2, 3], [4, 5, 6, 7, 8, 9]]

这是我的代码:

package test;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {

        List<String> list = new ArrayList<String>() {
            {
                add("Hi, ");                //0
                add("th");                  //1
                add("is ");                 //2
                add("text is a sample. ");  //3
                add("Hello ag");            //4
                add("ain, ");               //5
                add("this i");              //6
                add("s an");                //7
                add("other ");              //8
                add("text.");               //9
            }
        };
        
        
        String tmpText="";
        List<Integer> indexList = new ArrayList<Integer>();
        List<List> listOfLists = new ArrayList<List>();
        
        for(int i=0; i<list.size();i++) {
            tmpText = tmpText + list.get(i);
            indexList.add(i);
            if(tmpText.contains("text")) {
                System.out.println(tmpText);
                System.out.println("List of index: "+indexList + "\n");
                listOfLists.add(indexList);
                tmpText="";
                indexList.clear();
            }
        }
        System.out.println("List of Lists: "+listOfLists);
        
    }

}

1 个答案:

答案 0 :(得分:1)

将此语句 indexList.clear(); 替换为 indexList = new ArrayList<Integer>();

相关问题