Collections: Lists

 

Python

Java

 

A list is a mutable sequence of 0 or more objects of any type.

 

Lists have a literal representation, of the form

 

[<e0, e1, , en-1]

 

The len function returns the number of elements in a list.

 

The subscript operator ([]) accesses an element at a given position.

 

Example:

 

aList = [45, 56, 67]

 

print(len(aList), aList[2])

 

Lists of comparable objects can be compared using the standard comparison operators ==, <, etc.

 

The list class includes many useful methods for insertions, removals, searches, and so forth.

 

 

A list is a mutable sequence of 0 or more objects of any type.  A generic list constrains its elements to the same supertype.

 

The List interface includes the methods common to all implementing classes. 

 

The implementing classes include ArrayList and LinkedList.

 

A generic list specifies the element type of the list variable and the instantiated list object, as follows:

 

List<String> names = new ArrayList<String>();

List<Integer> ages = new LinkedList<Integer>();

 

Note first that both list variables are viewed as of type List, although they refer to instances of different list classes.  Both list objects will respond to any method in the List interface.

 

Note second that the first list can contain only strings, whereas the second list can contain only instances of class Integer.

 

Note third that the class Integer is a wrapper class, which allows values of type int to be stored in a list.  When an int is inserted into the second list, the JVM wraps it in an Integer object.  When an Integer object is accessed in this list, the int value contained therein is returned.

 

Example:

 

ages.add(63);

ages.set(0, ages.get(0) + 1);  // Increment age

 

Previous

Index

Next