How to Add Items to a LinkedList in Java
In Java, the LinkedList class gives you many ways to add items to the list. The most basic is the add method, which works pretty much the same way that it does for the ArrayList class. Here’s an example:
LinkedList<String> officers = new LinkedList<String>(); officers.add("Blake"); officers.add("Burns"); officers.add("Houlihan"); officers.add("Pierce"); officers.add("McIntyre"); for (String s : officers) System.out.println(s);
The add method adds these items to the end of the list. So the resulting output is this:
Blake Burns Houlihan Pierce McIntyre
The addLast method works the same way, but the addFirst method adds items to the front of the list. Consider these statements:
LinkedList<String> officers = new LinkedList<String>(); officers.addFirst("Blake"); officers.addFirst("Burns"); officers.addFirst("Houlihan"); officers.addFirst("Pierce"); officers.addFirst("McIntyre"); for (String s : officers) System.out.println(s);
Here the resulting output shows the officers in reverse order:
McIntyre Pierce Houlihan Burns Blake
To insert an object into a specific position into the list, specify the index in the add method, as in this example:
LinkedList<String> officers = new LinkedList<String>(); officers.add("Blake"); officers.add("Burns"); officers.add("Houlihan"); officers.add("Pierce"); officers.add("McIntyre"); officers.add(2, "Tuttle"); for (String s : officers) System.out.println(s);
The console output from these statements is this:
Blake Burns Tuttle Houlihan Pierce McIntyre
(In case you’re not a M*A*S*H fan, Tuttle was a fictitious officer that Hawkeye and Trapper made up in one episode so that they could collect his paychecks and donate the money to the local orphanage. Unfortunately, the ruse got out of hand. When Tuttle won a medal, and a general wanted to present it in person, they arranged for “Tuttle” to “die” in an unfortunate helicopter accident.)
Here are some other thoughts to consider when you ponder how to add elements to linked lists:
If you specified a type for the list when you created it, the items you add must be of the correct type. The compiler kvetches if they aren’t.
Like arrays and everything else in Java, linked lists are indexed starting with zero.
If you specify an index that doesn’t exist, the add method throws IndexOutOfBoundsException. This is an unchecked exception, so you don’t have to handle it.
LinkedList also has weird methods named offer, offerFirst, and offerLast. The offer method adds an item to the end of the list and has a return type of boolean, but it always returns true. The offer method is defined by the Queue interface, which LinkedList implements.
Some classes that implement Queue can refuse to accept an object added to the list via offer. In that case, the offer method returns false. But because a linked list never runs out of room, the offer method always returns true to indicate that the object offered to the list was accepted.