I\'m working on some piece of code, which is quite hot, and I need to add elements of one LinkedList
(l1
) to another LinkedList
(
It seems like required feature is not supported by the standard library. However, you can use reflection to achieve constant time when merging linked lists. I haven't tested the following code properly, just to show how it could be achieved:
public class ListConcatenation {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
LinkedList list1 = new LinkedList<>();
list1.add("a");
list1.add("b");
list1.add("c");
LinkedList list2 = new LinkedList<>();
list2.add("d");
list2.add("e");
list2.add("f");
System.out.println(merge(list1, list2));
}
public static List merge(List list1, List list2) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
Field first = getDeclaredField(LinkedList.class, "first");
Field last = getDeclaredField(LinkedList.class, "last");
Field size = getDeclaredField(LinkedList.class, "size");
Class> nodeClass = Class.forName("java.util.LinkedList$Node");
Field next = nodeClass.getDeclaredField("next");
next.setAccessible(true);
Object list1Last = last.get(list1);
Object list2First = first.get(list2);
Object list2Last = last.get(list2);
// link the last element of list1 with the first element of list2
next.set(list1Last, list2First);
// set last element of list1 equal to the last element of list2
last.set(list1, list2Last);
// update list1 size
size.set(list1, list1.size() + list2.size());
return list1;
}
private static Field getDeclaredField(Class> clazz, String name) throws NoSuchFieldException {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
}
}