Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit 301 Java Collections Framework: Classes I JCF Class Hierarchy The ArrayList Class The Collections Class.

Similar presentations


Presentation on theme: "Unit 301 Java Collections Framework: Classes I JCF Class Hierarchy The ArrayList Class The Collections Class."— Presentation transcript:

1 Unit 301 Java Collections Framework: Classes I JCF Class Hierarchy The ArrayList Class The Collections Class

2 Unit 302 Collections Framework’s Classes Object CollectionsAbstractCollection AbstractList AbstractSequentialList LinkedList ArrayList > Collection > List

3 Unit 303 The ArrayList Class The ArrayList class is List implementation based on a dynamic array. Thus, an ArrayList object is a dynamic array It extends the AbstractList class and implements the List interface of the JCF Before Java 1.2, the functionality of the ArrayList was provided by the Vector class. The Vector class is still part of the JCF. ArrayList is very much like the Vector class except that ArrayList methods are not synchronized Since this class is based on an array, it is better used in applications requiring fast direct access to objects However, the LinkedList class will give better performance for applications requiring frequent insertions and deletions

4 Unit 304 Example 1: Objects of a Collection This example shows that different objects can be added to the collection. 1 import java.util.ArrayList; 2 import java.util.Collections; 3 class ArrayListOfAllKinds{ 4 public static void main(String args []){ 5 ArrayList theArray = new ArrayList(); 6 theArray.add(new Double(3.7)); 7 theArray.add(new Boolean(true)); 8 theArray.add(new Integer(19)); 9 theArray.add(new String(";-)")); 10 System.out.print(“[“); 11 for(int i=0;i< theArray.size();i++) // loop can be made with iterator 12 System.out.print(theArray.get(i)+” “); 13System.out.println(“]”); 14// printing the whole arrayList object can be done in a single statement because toString() method is defined for the collection object 16 System.out.println(theArray); 17 } 18 }

5 Unit 305 Example 2: List of Lists This example shows that arrayList objects can be added to other arrayList objects. 1 import java.util.ArrayList; 2 class ListOfLists{ 3 public static void main(String s[]){ 4 ArrayList kfupm=new ArrayList(); 5 ArrayList ics=new ArrayList(); 6 ArrayList coe=new ArrayList(); 7 ArrayList mis=new ArrayList(); 8 String[] icsBasics={"ics102", "ics103", "ics201", "ics202"}; 9 String[] coeBasics={"coe200", "ics102", "ics201", "ics202"}; 10 String[] misBasics={"mis105", "mis345", "mis301", "ics201"}; 11 for (int i=0; i<icsBasics.length; i++) { 12 ics.add(icsBasics[i]); 13 coe.add(coeBasics[i]); 14 mis.add(misBasics[i]); 15 } 16 kfupm.add(ics); 17 kfupm.add(coe); 18 kfupm.add(mis); 19 System.out.println(kfupm); 20 } 21 }

6 Unit 306 Example 3: Using ArrayList The removeRange() method has protected access modifier in ArrayList. In order to use it, we can extend ArrayList class and override the method and make its access modifier public. 1 import java.util.*; 2 class MyArrayList extends ArrayList{ 3 public MyArrayList(int size){ // if we want to give initial capacity to our arrayList 4 super(size); 5 } 6 public void removeRange (int x, int y){ //protected method of ArrayList 7 super.removeRange(x,y); 8 } 9 } // end of MyArrayList class 10 class TestMyArrayList{ 11 public static void main(String s[]){ 12 MyArrayList c = new MyArrayList(100); //initial capacity. Don’t confusse with size() 13 ListIterator iter = c.listIterator(); 14 for(int i=0; i<6; i++) 15 iter.add(new Integer(i)); // using iterator's add 16 c.add(2,"ICS 201"); // using collection's add 17 System.out.println(c); 18 c.removeRange(3,6); // removes elements from index 3 to 5 19 System.out.println(c); 20 } 21 }

7 Unit 307 Example 4: Using ArrayList 1 import java.util.*; 2 class TestOtherMethods { 3 public static void main(String s[]){ 4 ArrayList c, c1, c2 = new ArrayList(), c3 = new ArrayList(); 5 ListIterator iter = c3.listIterator(); 6 for(int i=0; i<s.length; i++) 7 iter.add(s[i]); // adding through listIterator 8 for(int i=0; i<10; i++) 9 c2.add(new Integer(i)); // adding through add method of the arrayList object 10 Collections.shuffle(c2); // mix the elements of the arrayList c2 11 System.out.println("Shuffled: "+ c2); 12 c1 = new ArrayList(c3); // making c1 arrayList from the elements of arrayList c3 13 c2.addAll(3,c1); // inserting elements of c1 at index 3 off c2 14 c = (ArrayList)c2.clone(); // making a copy of c2 and storing its address in c 15 c.remove(3); // using remove of collection. Don’t mix with remove of iterator 16 System.out.println(c); 17 System.out.println(c1); 18 System.out.println(c2); 19 System.out.println(c3.containsAll(c1)); // check if all elements of c1 are present in c3 20 } 21 }

8 Unit 308 Example 5: Splitting arrayList alternatively import java.util.*; class SplitList { public static void main(String[] args) { ArrayList a=new ArrayList(); ArrayList b=new ArrayList();ArrayList c=new ArrayList(); Random rd=new Random(); for (int i=0;i<20;i++) a.add(new Integer(rd.nextInt(101)-50)); // generates random number between -50 and 50 Iterator ia = a.iterator(); // iterator for a //put elements of a alternatively in b and c while (ia.hasNext()) { b.add(ia.next()); if (ia.hasNext()) c.add(ia.next()); } System.out.println(a); System.out.println(b); System.out.println(c); }}

9 Unit 309 Example 6: removing similar objects import java.util.*; class RemoveSimilar { public static void main(String[] args) { String[] words={"apple","cat","pen","tea","tree","like","like","ics201"}; ArrayList myWords = new ArrayList(Arrays.asList(words)); ArrayList myWords2=(ArrayList)myWords.clone(); int n = myWords.size(); // for (int i = 0; i < n; i++) { // wrong way of making loop indexoutofBound exception for (int i=0;i<myWords.size();i++){ // still wrong, second like is skipped if ("like".equals(myWords.get(i))) myWords.remove(i); } System.out.println("One like word left --> "+myWords); // right way of making loop to remove all "like" words for(int i=0; i<myWords2.size();) { // the increment part empty if ("like".equals(myWords2.get(i))){ myWords2.remove(i);} else i++; } System.out.println("All like words removed --> "+myWords2); }}

10 Unit 3010 The Collections Class The Collections class is a utility class. It contains static methods for manipulating collection objects. Some of the methods were already used in previous examples. The Arrays class is also a utility class. It contains static methods for manipulating arrays. One useful method used is asList() to convert an array into a list. The following are the most frequently used methods of the Collections class. –static int binarySearch(List list, Object o) // list sorted according to natural ordering –static int binarySearch(List list, Object o, Comparator c)// list sorted according to comparator –static void sort(List list) // sorts according to natural ordering –static void sort(List list, Comparator c) // sorts according to comparator –static void copy (List dest, List src) // copies all elements from src list to dest list –static Object max(Collection c) // returns max according to natuaral ordering –static Object min(Collection c) // returns min according to natuaral ordering –static void reverse(List list) //Reverses the order of the elements in the specified list –static void shuffle(List list) // Randomly permutes the specified list The next example uses sort and binary search methods

11 Unit 3011 Example 7: Sorting arrayLists import java.util.*; import javax.swing.*; class SortingList { public static void main(String[] args) { ArrayList list = new ArrayList(); // Get the students' names String s; do{ s=JOptionPane.showInputDialog(null,"Student Name"); if (s!=null) list.add(s); }while(s!=null); // Sort the list in alphabetical order Collections.sort(l); // sorting based on compareTo method implemented by String class Iterator i = list.iterator(); while(i.hasNext()) System.out.println(i.next()); // Print the list using the iterator Collections.sort(l,new Comparator(){ // sort the list according to the comparator object public int compare(Object b1, Object b2) { return ((String)b1).length()-((String)b2).length(); }}); System.out.println("list sorted by length of name "+l); // print using toString() of arrayList }}

12 Unit 3012 Example 8: Searching Collections import java.util.*; class BankAccount implements Comparable{ private int accountNumber; private String name; private double balance; public BankAccount(int accountNumber, String name, double balance){ this.accountNumber = accountNumber; this.name = name; this.balance = balance; } public BankAccount(int accountNumber, String name){ this(accountNumber, name,0); } public String getName() { return name; } public int compareTo(Object object){ BankAccount account = (BankAccount) object; return accountNumber - account.accountNumber; } public String toString(){ return accountNumber + " " + name + " " + balance + " SR"; }

13 Unit 3013 Example 8: Searching Collections (cont’d) class SortingAndSearching{ public static void main(String[] args){ ArrayList list = new ArrayList(); list.add(new BankAccount(9234, "Ahmad", 50000 )); list.add(new BankAccount(8000, "Abubakar", 40000 )); list.add(new BankAccount(6000, "Yusuf", 6000 )); list.add(new BankAccount(9975, "Zubeir", 10000 )); System.out.println("Sorted in increasing order of Account Number:"); Collections.sort(list); System.out.println(list); System.out.println("Sorted in decreasing order of Customer name:"); Collections.sort(list, new Comparator(){ public int compare(Object object1, Object object2){ BankAccount account1 = (BankAccount) object1; BankAccount account2 = (BankAccount)object2; String string1 = account1.getName(); String string2 = account2.getName(); return string2.compareTo(string1); }}); System.out.println(list); Collections.sort(list); System.out.println("Sorted again in increasing order of Account Number: \n"+list); BankAccount ba1 = new BankAccount(6000, "Yusuf"); BankAccount ba2 = new BankAccount(1000, "Yassin"); System.out.println(Collections.binarySearch(list, ba1)); //present at index 0 System.out.println(Collections.binarySearch(list, ba2)); // not present (-1) printed }}


Download ppt "Unit 301 Java Collections Framework: Classes I JCF Class Hierarchy The ArrayList Class The Collections Class."

Similar presentations


Ads by Google