简体   繁体   中英

Replace part of ArrayList with other ArrayList

Is there any simple way (for example library function) to replace fragment of one ArrayList with another ArrayList? What I want to do is:

 ArrayList<Byte> fileArr = // some bytes //
 ArrayList<Byte> toReplace = // some bytes I want to replace in fileArray //
 ArrayList<Byte> window = // window with bytes from file and size of toReplace List  //
 ArrayList<Byte> replacing = // bytes I want to replace with //
 for(int i = 0; i <= (maxElementOfFileArray - sizeOfToReplace); i++){
 window = fileArr.subList(i, i+sizeOfToReplace) 
 if(window.equals(toReplace){
      fileArr.replaceAll(i, toReplace, replacing) 
 }
i= indexOfReplacingListFinishInFileList -1; 
}

where the replaceAll function would replace elements of file ArrayList from index where subList toReplace occurs with elements of replacing list, and here's the catch: toReplace and replacing may be diffrent size Lists. Because if they would be the same size I just would do that with set function of ArraList in "for(E e : elements)" . So replace function can change size of file ArrayList it's changing.

You could try

fileArr.removeRange(i, i+sizeOfToReplace);
fileArr.addAll(i, replacing);

You can clear, then add the new elements to the window.

By the ways you can use Collections.indexOfSubList to find the window position.

    List<Byte> fileArr = new ArrayList(Arrays.asList(new Byte[]{1, 2, 3, 4, 5, 6}));
    List<Byte> toReplace = Arrays.asList(new Byte[]{3, 4});
    List<Byte> replacing = Arrays.asList(new Byte[]{13, 14, 15, 16, 17, 18});

    int idx = Collections.indexOfSubList(fileArr, toReplace);

    if (idx >= 0) {
        List<Byte> window = fileArr.subList(idx, idx + toReplace.size());
        window.clear();
        window.addAll(replacing);
    }

    System.out.println(fileArr);


    [1, 2, 13, 14, 15, 16, 17, 18, 5, 6]

Write a utility method to accept a generic array and replace a given subarray, if found, with all the possible checks.

You can test for the presence of the subarray:

    int firstIndex = Collections.indexOfSubList(source, target);

    if (firstIndex == -1 ){
        // the sublist doesn't exist
    }

    int lastIndex = Collections.lastIndexOfSubList(source, target);

From there you have your insertion points and can use a library to insert or write a brute force method. For instance you can get the sublist from the List interface and make the changes to that sublist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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