CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Collections

Collections and Generics
LinkedList class
Code

Code that creates a linked list of type String

// create a linked list of type String
LinkedList codes = new LinkedList();

// add three strings
codes.add("mbdk");
codes.add("citr");
codes.add(0, "warp");

System.out.println(codes);

Resulting output

 [warp, mbdk, citr]

Code that adds elements to the beginning and end of the linked list

codes.addFirst("wuth");
codes.addLast("wooz");

System.out.println(codes);

Resulting output

 [wuth, warp, mbdk, citr, wooz]

Code that uses an enhanced for loop to process the linked list

for (String s : codes)
    System.out.println(s);

Resulting output

wuth
warp
mbdk
citr
wooz

Code that retrieves the first and last elements of the linked list

String firstString = codes.removeFirst();
String lastString = codes.removeLast();
System.out.println(firstString);
System.out.println(lastString);
System.out.println(codes);

Resulting output

wuth
wooz
[warp, mbdk, citr]
Previous | Class | Code | Chain of nodes | Stacks and Queues | Generic queue | ArrayList and LinkedList | Next