java replace list with sublist
I have a list
ArrayList list = new ArrayList(Arrays.asList(1,2,3,4,5,3,4,2,4,5,3,10));
And I have another sublist
ArrayList sublist = new ArrayList(Arrays.asList(4,5,3));
I was looking around for a functionality to replace the sublist inside list
with another sublist
ArrayList sublist开发者_如何学C = new ArrayList(Arrays.asList(100,100)));
so after the find and replace , the new list should become :
list = (1,2,3,100,100,4,2,100,100,10);
I could not find any api for this one in java.
Not sure if there exists any api for doing this or not, but what you could do is take advantage of the List interface in Java.
If you combine the use of containsAll(Collection c) Returns true if this list contains all of the elements of the specified collection.
removeAll(Collection c) Removes from this list all of its elements that are contained in the specified collection (optional operation).
and
addAll(int index, Collection c) Inserts all of the elements in the specified collection into this list at the specified position (optional operation).
I think you can easily accomplish what you need.
Take a look here: http://download.oracle.com/javase/6/docs/api/java/util/List.html
If you create the sublist as a true sublist of list
, e.g. using List#subList()
, then (non-structural) changes made to sublist
will be reflected in list
.
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 3, 4, 2, 4, 5, 3, 10);
List<Integer> sublist = list.subList(3, 6);
for (int i=0; i<sublist.size(); i++)
{
sublist.set(i, 100);
}
System.out.println(sublist);
// prints 100, 100, 100
System.out.println(list);
// prints 1, 2, 3, 100, 100, 100, 4, 2, 4, 5, 3, 10
Demo: http://ideone.com/ljvd0
Lists.newArrayList(...)
comes from Google Guava.
精彩评论