Explain what the following code does (i.e. comment each line of the code) import
ID: 3565888 • Letter: E
Question
Explain what the following code does (i.e. comment each line of the code)
import java.util.LinkedList;
public class Merge {
public static void main(String[] args) {
LinkedList<Integer> l1=new LinkedList<>();
LinkedList<Integer> l2=new LinkedList<>();
l1.add(3);
l1.add(1);
l1.add(6);
l2.add(2);
l2.add(8);
l2.add(5);
LinkedList<Integer> l3=Merge.merge(l1, l2);
}
public static LinkedList<Integer> merge(LinkedList<Integer> l1,LinkedList<Integer> l2)
{
LinkedList<Integer> l3=null;
l3.addAll(l1);
l3.addAll(l2);
return l3;
}
}
Explanation / Answer
//importing LinkedList class from util package
import java.util.LinkedList;
public class Merge {
public static void main(String[] args) {
// creating Generic LinkedList class of Integer type object(l1)
LinkedList<Integer> l1=new LinkedList<>();
// creating Generic LinkedList class of Integer type object(l2)
LinkedList<Integer> l2=new LinkedList<>();
l1.add(3); // adding item "3" to the LinkedList l1
l1.add(1); // adding item "1" to the LinkedList l1
l1.add(6); // adding item "6" to the LinkedList l1
l2.add(2); // adding item "2" to the LinkedList l2
l2.add(8); // adding item "8" to the LinkedList l2
l2.add(5); // adding item "5" to the LinkedList l2
// calling static method merge() which returns the LinkedList object
LinkedList<Integer> l3=Merge.merge(l1, l2);
}
// merge() method which takes input parameters as 2 linkedlist objects and returns linkedlist object
public static LinkedList<Integer> merge(LinkedList<Integer> l1,LinkedList<Integer> l2)
{
//creating linkedlist reference l3 and initializing it to null
LinkedList<Integer> l3=null;
l3.addAll(l1); // adding all the elements l1 object to l3
l3.addAll(l2); // adding all the elements l2 object to l3
return l3; // returning l3 object to calling method
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.