Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 5 ArrayLists.

Similar presentations


Presentation on theme: "CHAPTER 5 ArrayLists."— Presentation transcript:

1 CHAPTER 5 ArrayLists

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27 FROM THE AbstractList CLASS: public boolean add(Object o) { add(size(), o); return true; } abstract public Object get(int index); public void add(int index, Object element) { throw new UnsupportedOperationException(); }

28 WHAT’S THE DIFFERENCE BETWEEN AN ABSTRACT METHOD AND A METHOD WHOSE DEFINITION THROWS AN EXCEPTION? ANY SUBCLASS OF AbstractList MUST DEFINE THE get METHOD IN ORDER TO BE INSTANTIABLE, BUT NEED NOT DEFINE THE TWO-PARAMETER add METHOD AS LONG AS THAT METHOD IS NOT INVOKED (AND THE ONE-PARAMETER add METHOD IS NOT INVOKED).

29

30

31

32

33

34

35 FIELDS IN THE ArrayList CLASS private transient Object[ ] elementData; // “transient” means that the array elementData need // not be saved if the ArrayList object is serialized. The // individual elements will be saved, but not the array. private int size;

36 // Postcondition: this ArrayList object has been initialized // to be empty and with a capacity given // by initialCapacity. public ArrayList (int initialCapacity) { elementData = new Object [initialCapacity]; } // constructor with int parameter

37 // Postcondition: this ArrayList object has been initialized // to be empty. public ArrayList ( ) { this (10); }

38 // Postcondition: o has been appended to this ArrayList // object and true has been returned. The // averageTime(n) is constant and // worstTime(n) is O (n). public boolean add (Object o) { ensureCapacity (size + 1); elementData [size++] = o; return true; }

39 public void ensureCapacity(int minCapacity) { int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { // Increase the capacity by at least 50%, // and copy the old array to the new array. }

40 public void ensureCapacity(int minCapacity) { modCount++; // discussed below int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3) / 2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; elementData = new Object[newCapacity]; System.arraycopy(oldData, 0, elementData, 0, size); }

41 public Object clone() { try { ArrayList v = (ArrayList)super.clone(); // copies size v.elementData = new Object[size]; System.arraycopy(elementData, 0, v.elementData, 0, size); v.modCount = 0; // the modCount field is // discussed later return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }

42 // Postcondition: this ArrayList has been initialized to a // copy of c. public ArrayList(Collection c) { this((c.size()*110)/100); // Allow 10% room for growth Iterator i = c.iterator( ); while (i.hasNext( )) elementData[size++] = i.next(); } NOTE: THIS IS CALLED THE COPY CONSTRUCTOR.

43 HERE ARE TWO WAYS TO CREATE A COPY OF myList : ArrayList newList = (ArrayList)myList.clone( ); ArrayList newList = new ArrayList (myList); SUPPOSE myList HAS 3 ELEMENTS:

44 Clone Copy Constructor A1 A2 A3 A1 A2 A3 null null null null null null null

45

46

47 ITERATORS – NOT NEEDED FOR ArrayList S for (int j = 0; j < myList.size( ); j++) gui.println (myList.get (j));

48 BUT ITERATORS ARE LEGAL: Iterator itr = myList.iterator( ); while (itr.hasNext( )) gui.println (itr.next( ));

49 INHERITED FROM AbstractList : protected transient int modCount = 0;

50 THE modCount FIELD IS INCREMENTED EVERY TIME THE ArrayList IS STRUCTURALLY MODIFIED, THAT IS, WITH AN INSERTION OR REMOVAL.

51 EACH ITERATOR CLASS IN THE JAVA COLLECTIONS FRAMEWORK HAS A FIELD: int expectedModCount = modCount;

52 public Object next( ) { … checkForComodification( );

53 final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }

54 THE ITERATOR FAILS AS SOON AS IT IS DISCOVERED THAT ANOTHER OBJECT – EITHER ANOTHER ITERATOR OR THE ArrayList OBJECT ITSELF – HAS STRUCTURALLY MODIFIED THE ArrayList OBJECT.

55 FOR THAT REASON, ITERATORS IN THE JAVA COLLECTIONS FRAMEWORK ARE CALLED FAIL-FAST ITERATORS

56 FOR EXAMPLE, THE FOLLOWING CODE WILL THROW ConcurrentModificationException: public ModCountDriver( ) { ArrayList list = new ArrayList( ); list.add (“yes”); Iterator itr = list. iterator( ); list.add (“good”); itr.next( ); // exception thrown at this point } // default constructor

57 BASICALLY, ONCE YOU CONSTRUCT AN ITERATOR, YOU SHOULD NOT ADD OR REMOVE FROM THE COLLECTION EXCEPT THROUGH THE ITERATOR’S METHODS.

58 EXERCISE: WHAT ARE THE VALUES OF modCount AND expectedModCount WHEN THE next( ) METHOD IS CALLED IN THE ABOVE CONSTRUCTOR?

59 APPLICATION HIGH-PRECISION ARITHMETIC

60 IN PUBLIC-KEY CRYPTOGRAPHY, THE INTEGERS ARE HUNDREDS OF DIGITS LONG.

61 KEY FACTS: 1. TO GENERATE A VERY LONG INTEGER THAT IS PRIME, averageTime(n) IS O ((log n) 3 ). IF n = 10 200, (log 10 n) 3 = 200 3 = 8,000,000.

62 2. TO FACTOR A VERY LONG INTEGER THAT IS NOT PRIME, averageTime(n) IS ABOUT n 1/ 2. IF n = 10 200, n 1/2 = 10 100.

63 3. GIVEN PRIMES p AND q, (p – 1)(q – 1) IS USED TO ENCODE A PUBLIC MESSAGE.

64 4. TO DECODE THE MESSAGE, p AND q MUST BE KNOWN.

65 WE WILL NOW DEVELOP A VeryLongInt CLASS TO HANDLE VERY LONG INTEGERS. IN THE METHOD DESCRIPTIONS, n REFERS TO THE NUMBER OF DIGITS IN THE CALLING OBJECT.

66 // Postcondition: this VeryLongInt is empty. public VeryLongInt( ); // Precondition: the string s consists of a sequence of // characters, with non-digit characters // ignored. There are no leading zeroes, // except for 0 itself, which has a single '0'. // The worstTime (n) is O (n). // Postcondition: this VeryLongInt has been initialized // from s. public VeryLongInt (String s);

67 // Postcondition: a String representation of this // VeryLongInt has been returned. The // worstTime (n) is O (n). public String toString(); // Postcondition: This VeryLongInt has been // incremented by otherVeryLong. // The worstTime (n) is O (n). public void add (VeryLongInt otherVeryLong);

68

69 FOR EXAMPLE, THE FOLLOWING CODE CONSTRUCTS TWO VeryLongInt OBJECTS WITH VALUES 345 AND 6789 AND PRINTS OUT THEIR SUM.

70 VeryLongInt very1 = new VeryLongInt (“345”); VeryLongInt very2 = new VeryLongInt (“6789”); very1.add (very2); gui.println (very1); // = gui.println (very1.toString( ));

71 FIELDS AND METHOD DEFINITIONS FOR THE VeryLongInt CLASS THE ONLY FIELD IS: ArrayList digits; // holds all of the digits // in the VeryLongInt

72 public VeryLongInt( ) { final int INITIAL_CAPACITY = 500; digits = new ArrayList (INITIAL_CAPACITY); } // default constructor

73 public VeryLongInt (String s) { // FOR EACH CHARACTER c IN s, //IF ‘0’ <= c <= ‘9’ //APPEND (c – ‘0’) TO digits. } // constructor with string parameter SUPPOSE s = “3x79”. WHAT WILL digits CONTAIN?

74 public String toString( ) { final String EMPTY_STRING = ""; String s = EMPTY_STRING; for (int i = 0; i < digits.size(); i++) s += digits.get (i); return s; } // method toString

75 FOR THE add METHOD: VeryLongInt a1, a2; // a1 = {3, 8, 7, 4, 9, 8} // a2 = {5, 3, 6, 4} a1.add (a2);

76 LOOP 6 TIMES: 0: 8 + 4 = 12 APPEND 2, AND THE CARRY IS 1. 1: 9 + 6 + 1 (THE CARRY) = 16 APPEND 6 AND THE CARRY IS 1.... WE END UP WITH 268293, SO REVERSE.

77 public void add (VeryLongInt otherVeryLong) { final int BASE = 10; int largerSize, partialSum, carry = 0; VeryLongInt sum = new VeryLongInt(); if (digits.size() > otherVeryLong.digits.size()) largerSize = digits.size(); else largerSize = otherVeryLong.digits.size();

78 for (int i = 0; i < largerSize; i++) { // Add the ith least significant digit in the // calling object, the ith least significant digit // in otherVeryLong, and the carry. // Append that sum % 10 to sum.digits // The new carry is that sum / 10. } // for if (carry == 1) sum.digits.add (new Integer (carry)); Collections.reverse (sum.digits); digits = sum.digits; } // method add

79 for (int i = 0; i < largerSize; i++) { partialSum = least (i) + otherVeryLong.least (i) + carry; sum.digits.add (new Integer ( partialSum % BASE)); carry = partialSum / BASE; } // for if (carry == 1) sum.digits.add (new Integer (carry)); Collections.reverse (sum.digits); digits = sum.digits; } // method add

80 SUPPOSE THE VeryLongInt OBJECT HAS THE VALUE 13579. THEN least (0) RETURNS 9 least (1) RETURNS 7 least (2) RETURNS 5 least (3) RETURNS 3 least (4) RETURNS 1 least (5) RETURNS 0

81 // Postcondition: If i >= digits.size(), 0 has been returned; // else the ith least significant digit in // digits has been returned. The rightmost // digit is the 0th least significant digit. private int least (int i) { if (i >= digits.size()) return 0; else return ((Integer)(digits.get ( digits.size() - i - 1))).intValue (); } // least

82 HOW LONG DOES THE add METHOD TAKE, ON AVERAGE? RECALL THAT n REFERS TO THE NUMBER OF DIGITS.

83

84 EXERCISE: FOR THE FOLLOWING ADDITION, SHOW THE FINAL CONTENTS OF a1.digits.elementData : // a1 = {3, 8, 7, 4, 9, 8} // a2 = {5, 3, 6, 4} a1.add (a2);


Download ppt "CHAPTER 5 ArrayLists."

Similar presentations


Ads by Google