将两个arraylists加入一个

use*_*159 11 java arraylist

我想检查branchList是否有相同的元素,如果相同,将branchList和tglList元素分开arraylist并将该arraylist放入另一个arraylist,

我想要的结果是BranchList1有2个arraylist,其中第一个arraylist包含元素'1',第二个arraylist包含元素'2',TglList1有2个arraylist作为元素,但我得到的是第1和第2个数组得到相同的值.

如何才能做到这一点?

ArrayList branchList = new ArrayList();
    branchList.add("1");
    branchList.add("1");
    branchList.add("1");
    branchList.add("2");
    branchList.add("2");
    branchList.add("2");

    ArrayList tglList = new ArrayList();
    tglList.add("5");
    tglList.add("10");
    tglList.add("20");
    tglList.add("100");
    tglList.add("500");
    tglList.add("1000");


    ArrayList newBranchList = new ArrayList();
    ArrayList newTglList = new ArrayList();

    ArrayList BranchList1 = new ArrayList();
    ArrayList TglList1 = new ArrayList();


    ArrayList abc = new ArrayList();
    String checkBranch = new String();

    for(int i=0;i<branchList.size();i++){
        String branch = branchList.get(i).toString();
        if(i==0 || checkBranch.equals(branch)){
            newBranchList.add(branch);
            newTglList.add(tglList.get(i).toString());
        }else{
            BranchList1.add(newBranchList);
            TglList1.add(newTglList);

            newBranchList.clear();
            newTglList.clear();

            newBranchList.add(branch);
            newTglList.add(tglList.get(i).toString());
        }
        if(i==(branchList.size()-1)){
            BranchList1.add(newBranchList);
            TglList1.add(newTglList);
        }
        checkBranch = branch;
    }

}
Run Code Online (Sandbox Code Playgroud)

所以预期的结果如下:

BranchList1 = [ [1,1,1],[2,2,2]]
TglList1 = [[5,10,20],[50,100,200]]
Run Code Online (Sandbox Code Playgroud)

但我得到的是

BranchList1 = [ [2,2,2],[2,2,2]]
TglList1 = [[50,100,200],[50,100,200]]
Run Code Online (Sandbox Code Playgroud)

我该如何修改代码

Tho*_*mas 30

我没有彻底通过您的代码阅读(我不太明白你问什么了),但如果要合并(添加的元素)branchList,并tglListTglList1,试试这个:

TglList1.addAll(branchList);
TglList1.addAll(tglList);
Run Code Online (Sandbox Code Playgroud)

之后,TglList1应该包含两个列表的所有元素.如果您需要对列表进行排序,您可能需要Collections.sort(TglList1)事后调用(只需注意排序字符串可能在"2"之前放置"100",因为"1"在词法上小于"2").