Java Reference
In-Depth Information
T ABLE 11.1
Differences and Similarities between Arrays and ArrayList
Operation
Array
ArrayList
Creating an array/ArrayList
String[] a = new String[ 10 ]
ArrayList<String> list = new ArrayList<>();
Accessing an element
a[index]
list.get(index);
Updating an element
a[index] = "London" ;
list.set(index, "London" );
Returning size
a.length
list.size();
Adding a new element
list.add( "London" );
Inserting a new element
list.add(index, "London" );
Removing an element
list.remove(index);
Removing an element
list.remove(Object);
Removing all elements
list.clear();
You cannot use the get and set methods if the element is not in the list. It is easy to add,
insert, and remove elements in a list, but it is rather complex to add, insert, and remove ele-
ments in an array. You have to write code to manipulate the array in order to perform these
operations.
Suppose you want to create an ArrayList for storing integers. Can you use the following
code to create a list?
ArrayList< int > list = new ArrayList< int >();
No. This will not work because the elements stored in an ArrayList must be of an object
type. You cannot use a primitive data type such as int to replace a generic type. However,
you can create an ArrayList for storing Integer objects as follows:
ArrayList<Integer> list = new ArrayList<Integer>();
Listing 11.9 gives a program that prompts the user to enter a sequence of numbers and dis-
plays the distinct numbers in the sequence. Assume that the input ends with 0 and 0 is not
counted as a number in the sequence.
L ISTING 11.9 DistinctNumbers.java
1 import java.util.ArrayList;
2 import java.util.Scanner;
3
4 public class DistinctNumbers {
5 public static void main(String[] args) {
6 ArrayList<Integer> list = new ArrayList<Integer>();
7
8 Scanner input = new Scanner(System.in);
9 System.out.print( "Enter integers (input ends with 0): " );
10
create an array list
int value;
11
12 do {
13 value = input.nextInt(); // Read a value from the input
14
15
contained in list?
add to list
if (!
list.contains(value)
&& value != 0 )
16
list.add(value);
// Add the value if it is not in the list
17 } while (value != 0 );
 
Search WWH ::




Custom Search