Вы находитесь на странице: 1из 6

An array is a collection of variables of the same type. Creating an Array of Primitives 1. Declaration: int[] powers; 2.

Creation: powers = new int[4]; 3. Initialization: powers[0] = 1; Creating an Array of Object References 1. Declaration: String[] categories; 2. Creation: categories = new String[3]; 3. Initialization: length Property
String[] arr = new String[4]; for (inti = 0; i<arr.length; i++) { arr[i] = new String(); }

You can declare and create an array in the same statement:


int[] powers = new int[4];

You can declare and create an array in the same statement:


String[] categories = new String[3];

Create and initialize arrays at the same time:


int[] primes = {2, 3, 5, 7};

Create and initialize arrays at the same time:


String[] categories = {"Action", "Comedy", "Drama"};

Use a Loop to explore each element in the array


for (inti = 0;i <categories.length; i++){ System.out.println("Category: "+categories[i]); } for (String category: categories) { System.out.println ("Category: " +category); }

Arrays and Exceptions 1. ArrayIndexOutOfBoundsException 2. NullPointerException

Java Collections Framework The Collection interface is an abstraction representing a group of elements. The Set interface is a collection that cannot contain duplicate elements. The List interface: to allow duplicate elements to be stored in a collection, you need to use a list. A list can not only store duplicate elements, but also allows the user to specify where they are stored. The user can access elements via an index. The Map interface represents an object that maps one or more keys to their values. Maps do not contain duplicate keys, and each key maps to a single value. Sorted collections are provided through the SortedSet and SortedMap interfaces. Sets are more efficient than lists for storing nonduplicate elements. Lists are useful for accessing elements through the index.

The Collection Interface and the AbstractCollection Class add method adds an element to the collection addAll method adds all the elements in the specified collection to this collection remove() removes an element from the collection removeAll() removes the elements from this collection that are present in the specified collection retainAll method retains the elements in this collection that are also present in the specified collection. clear method simply removes all the elements from the collection. All these methods return boolean. The return value is true if the collection is changed as a result of the method execution. size method returns the number of elements in the collection. contains method checks whether the collection contains all the elements in the specified collection. isEmpty method returns true if the collection is empty.

Iterator Interface Provides a uniform way for traversing elements in various types of collections.
importjava.util.ArrayList; importjava.util.Iterator; .. .. ArrayList al = new ArrayList(); al.add("Jazz"); al.add("Classical"); al.add("Rock 'n Roll"); for (Iterator e = al.iterator(); e.hasNext(); ) { String s = (String)e.next(); System.out.println(s.toUpperCase()); }

The Set interface extends the Collection interface. Three concrete classes of Set are: HashSet: stores elements in an unpredictable order LinkedHashSet: stores elements in the order they were inserted TreeSet: stores elements sorted

HashSet
import java.util.HashSet; import java.util.Set; public class TestHashSet { public static void main(String[] args) { //Create a hash set Set<String> set = new HashSet<String>(); //Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); set.add("New York"); System.out.println(set); //Display the elements in the hash set for (Object element : set) System.out.print(element.toString() + " "); } } Output [San Francisco, New York, Paris, Beijing, London] San Francisco New York Paris Beijing London

LinkedHashSet
import java.util.LinkedHashSet; import java.util.Set; public class TestLinkedHashSet { public static void main(String[] args) { //Create a linked hash set Set<String> set = new LinkedHashSet<String>(); //Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); set.add("New York"); System.out.println(set); //Display the elements in the linked hash set for (Object element : set) System.out.print(element.toString() + " "); } } Output [London, Paris, New York, San Francisco, Beijing] London Paris New York San Francisco Beijing

TreeSet TreeSet is a concrete class that implements the SortedSet interface.


importjava.util.HashSet; importjava.util.Set; importjava.util.TreeSet; public class TestTreeSet { public static void main(String[] args) { //Create a hash set Set<String> set = new HashSet<String>(); //Add strings to the set set.add("London"); set.add("Paris"); set.add("New York"); set.add("San Francisco"); set.add("Beijing"); set.add("New York"); TreeSet<String>treeSet = new TreeSet<String>(set); System.out.println(treeSet); //Display the elements in the hash set for (Object element : set) System.out.print(element.toString() + " "); } } Output [Beijing, London, New York, Paris, San Francisco] San Francisco New York Paris Beijing London

LISTS The List interface has the following methods: add(index, element) Adds an new element at the specified index addAll(index, collection) Inserts a collection at the specified index remove(index) Removes an element at the specified index from the list set(index, element) Sets a new element at the specified index listIterator Returns the list iterator for the elements in this list listIterator(startIndex) Returns the iterator for the elements from startIndex ArrayList Stores elements in an array Is a resizable implementation of the List interface Allows manipulation of the array size Has capacity that grows as elements are added to the list To create an empty ArrayList: ArrayList members = new ArrayList();

Modifying an ArrayList Add an element to the end of the ArrayList:


String name = MyMovie.getNextName(); members.add(name);

Accessing an ArrayList Get the first element:


String s = members.get(0);

Get an element at a specific position: Add an element at a specific position:


// Insert a string at the beginning members.add(0, name); String s = members.get(2);

Find an object in an ArrayList:


int position = members.indexOf(name);

Remove the element at a specific index:


// Remove the first element members.remove(0);

Get the size of an ArrayList:


int size = members.size();

You can combine different types in an ArrayList. Here is a simple example:


ArrayList al = new ArrayList(); al.add(pat); al.add(10); al.add(123456.789); System.out.println(al); // to print the ArrayList

LinkedList ArrayList is efficient for retrieving elements and for inserting and removing elements from the end of the list.
importjava.util.ArrayList; importjava.util.LinkedList; importjava.util.List; importjava.util.ListIterator; public class TestArrayAndLinkedList{ public static void main(String[] args) { List<Integer>arrayList = new ArrayList<Integer>(); arrayList.add(1); //1 is autoboxed to new Integer(1) arrayList.add(2);

LinkedList is efficient for inserting and removing elements anywhere in the list.

arrayList.add(3); arrayList.add(1); arrayList.add(4); arrayList.add(0, 10); arrayList.add(3, 30); System.out.println("A list of integers in the array list:"); System.out.println(arrayList); LinkedList<Object>linkedList = new LinkedList<Object>(arrayList); linkedList.add(1, "red"); linkedList.removeLast(); linkedList.addFirst("green"); System.out.println("Display the linked list forwards:"); ListIteratorlistIterator = linkedList.listIterator(); while (listIterator.hasNext()) { System.out.print(listIterator.next() + " "); } System.out.println(); System.out.println("Display the linked list backwards:"); listIterator = linkedList.listIterator(linkedList.size()); while (listIterator.hasPrevious()) { System.out.print(listIterator.previous() + " "); } } } Output A list of integers in the array list: [10, 1, 2, 30, 3, 1, 4] Display the linked list forwards: green 10 red 1 2 30 3 1 Display the linked list backwards: 1 3 30 2 1 red 10 green

MAPS Query Methods containsKey(Object key) method checks whether the map contains a mapping for the specified key. containsValue(Object value) method checks whether the map contains a mapping for this value. isEmpty() method checks whether the map contains any mappings. size() method returns the number of mappings in the map. Update Methods clear() method removes all mappings from the map. put(Object key, Object value) method associates the specified value with the specified key in the map. If the map formerly contained a mapping for this key, the old value associated with the key is returned. putAll(Map m) method adds the specified map to this map. remove(Object key) method removes the map elements for the specified key from the map.

You can obtain a set of the keys in the map using the keySet method and a collection of the values in the map using the values method. The entrySet method returns a collection of objects that implement the Map.Entry interface, where Entry is an inner interface for the Map interface. Types of Maps HashMap is efficient for locating a value, inserting an entry and deleting an entry. Entries are not ordered. LinkedHashMap supports ordering of the entries in a map. TreeMap is efficient for traversing the keys in a sorted order.

The program first creates a hash map with the student's name as its key and the age as its value. It then creates a tree map from the hash map and displays the mappings in ascending order of the keys. Finally, it creates a linked hash map, adds the same entries to the map, and displays the entries.
importjava.util.HashMap; importjava.util.LinkedHashMap; importjava.util.Map; importjava.util.TreeMap; public class testMap{ public static void main(String[] args) { // Create a HashMap Map<String, Integer>hashMap = new HashMap<String, Integer>(); hashMap.put("Smith", 30); hashMap.put("Anderson", 31); hashMap.put("Lewis", 29); hashMap.put("Cook", 29); System.out.println("Display entries in HashMap"); System.out.println(hashMap); //Create a TreeMap from the HashMap Map<String, Integer>treeMap = new TreeMap<String, Integer>(hashMap); System.out.println("\nDisplay entries in ascending order of key"); System.out.println(treeMap); //Create a LinkedHashMap Map<String, Integer>linkedHashMap = new LinkedHashMap<String, Integer>(16, 0.75f, true); linkedHashMap.put("Smith", 30); linkedHashMap.put("Anderson", 31); linkedHashMap.put("Lewis", 29); linkedHashMap.put("Cook", 29); //Display the age for Lewis System.out.println("The age for " + "Lewis is " + linkedHashMap.get("Lewis").intValue()); System.out.println("\nDisplay entries in LinkedHashMap"); System.out.println(linkedHashMap); } } Output Display entries in HashMap {Smith=30, Lewis=29, Anderson=31, Cook=29} Display entries in ascending order of key {Anderson=31, Cook=29, Lewis=29, Smith=30} The age for Lewis is 29 Display entries in LinkedHashMap {Smith=30, Anderson=31, Cook=29, Lewis=29}

When you run the program you will see that the entries in the HashMap are in random order. The entries in the TreeMap are in increasing order of the keys. The entries in the LinkedHashMap are in the order of their access, from the least recently accessed to the most recently accessed.