java list

A List is a linear structure where each element is known by an index number 0, 1, 2, … len-1 (like an array). Lists can only store objects, like String and Integer, but not primitives like int

The List is probably the single most useful and widely used type of Collection. List is a general interface, and ArrayList and LinkedList are implementing classes. ArrayList is the best general purpose List

Basic List

code to create a new list to contain Strings:

List<String> words = new ArrayList();

The “words” variable is declared to be type “List” — “List” being the general interface for all lists, and the “” is the generic syntax means this is a list that contains

List add()

A new ArrayList is empty. The add() method adds a single element to the end of the list

words.add(“this”);
words.add(“and”);
words.add(“that”);
// words is now: {“this”, “and”, “that”}
words.size() // returns 3

The size() method returns the int size of a list (or any collection)

For all the collection classes, creating a new one with the default constructor gives you an empty collection. However, you can also call the constructor passing an existing collection argument, and this creates a new collection that is a copy. So we could copy the elements from words into a second list like this

// Create words2 which is a copy of words
List<String> words2 = new ArrayList<String>(words);

List Foreach

int lengthSum = 0;
for (String str: words) {
 lengthSum += str.length();
}

List get()

The get(int index) method returns an element by its index number

// suppose words is {"this", "and", "that"}
words.get(0) // returns "this"
words.get(2) // returns "that"
words.get(3) // ERROR index out of bounds

List For Loop

for (int i=0; i<words.size(); i++) {
 String str = words.get(i);
 // do something with str
}

Basic List Methods

Here are other basic list methods that works to set/add/remove elements in a list using index numbers to identify elements (these methods work on Lists but not on general Collection types which don’t have index numbers):

  • get(int index) ) — returns the element at the given index
  • set(int index, Object obj) — sets the element at the given index in a list (the opposite of get). Set() does not change the length of the list, it just changes what element is at an index.
  • add(Object obj) adds a new element at the end of the list.
  • add(int index, Object obj) — adds a new element into the list at the given index, shifting any existing elements at greater index positions over to make a space
  • remove(int index) — removes the element at the given index, shifting any elements at greater index positions down to take up the space.

Leave a Comment