1 / 22

ArrayLists

ArrayLists. Arrays in Java. Java has built in arrays as well as more complicated classes to automate many array tasks (the ArrayList class) arrays hold elements of the same type primitive data types or classes

tamarap
Télécharger la présentation

ArrayLists

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ArrayLists

  2. Arrays in Java • Java has built in arrays as well as more complicated classes to automate many array tasks (the ArrayList class) • arrays hold elements of the same type • primitive data types or classes • space for array must be dynamically allocated with new operator. (Size is any integer expression. Due to dynamic allocation does not have to be a constant.)

  3. public void arrayExamples() { int[] intList = new int[10]; for(int i = 0; i < intList.length; i++) { assert 0 >= i && i < intList.length; intList[i] = i * i * i; } intList[3] = intList[4] * intList[3]; }

  4. Array Details • all arrays must be dynamically allocated • arrays have a public, final field called length • built in size field, no separate variable needed • don't confuse length (capacity) with elements in use • elements start with an index of zero, last index is length - 1

  5. Array Initialization • Array variables are object variables • They hold the memory address of an array object • The array must be dynamically allocated • All values in the array are initialized (0, 0.0, char 0, false, or null) • Arrays of primitives and Strings may be initialized with an initializer list: int[] intList = {2, 3, 5, 7, 11, 13}; double[] dList = {12.12, 0.12, 45.3}; String[] sList = {"Olivia", "Kelly", "Isabelle"};

  6. Arrays of objects • A native array of objects is actually a native array of object variables • all object variables in Java are really what? • Pointers! public void objectArrayExamples() { Rectangle[] rectList = new Rectangle[10]; // How many Rectangle objects exist? rectList[5].setSize(5,10); //uh oh! for(int i = 0; i < rectList.length; i++) { rectList[i] = new Rectangle(); } rectList[3].setSize(100,200); }

  7. ArrayLists and arrays • A ArrayList is like an array of Objects • Differences between arrays and ArrayLists: • Arrays have special convenience syntax; ArrayLists don’t • An array is a fixed size, but a ArrayList expands as you add things to it • This means you don’t need to know the size beforehand • Arrays can hold primitives or objects, but ArrayLists can only hold objects • However, autoboxing can make it appear that an ArrayList can hold primitives

  8. Arrays in Java The ArrayList Class • A class that is part of the Java Standard Library and a class that is part of the AP subset • a kind of automated array • not all methods are part of the ap subset

  9. Arrays in Java About Lists (in general) • A list is an ordered collection or a sequence. • ArrayList implements the List interface • The user of this interface will have control over where in the list each element is inserted. • The user can access elements by their integer index (position in the list), and search for elements in the list. • Items can be added, removed, and accessed from the list

  10. Arrays in Java Methods • ArrayList() //constructor • void add(int index, Object x) • boolean add(Object x) • Object set(int index, Object x)               • Object remove(int index) • int size () • Object get(int index)   • Iterator iterator()                 

  11. Arrays in Java How the methods work • add: • boolean add(Object x) – inserts the Object x at the end of the list (size increases by 1), returns true • void add(int index, Object x) – inserts the Object x at the given index position (elements will be shifted to make room and size increases by 1)

  12. Arrays in Java How the methods work • get: • returns the Object at the specified index • should cast when using value returned • throws IndexOutOfBoundsException if index<0 or index>=size

  13. Arrays in Java How the methods work • set • replaces value of Object parameter at the given index • size is not changed

  14. Arrays in Java How the methods work • remove • removes the element at the specified index • throws IndexOutOfBoundsException if index<0 or index>=size • size will be decreased by 1 • returns Object removed

  15. Creating a ArrayList the new way • Specify, in angle brackets after the name, the type of object that the class will hold • Examples: • ArrayList<String> vec1 = new ArrayList<String>(); • ArrayList<String> vec2 = new ArrayList<String>(10); • To get the old behavior, but without the warning messages, use the <?> wildcard • Example: ArrayList<?> vec1 = new ArrayList<?>();

  16. Adding elements to a ArrayList • boolean add(Object obj) • Appends the object objto the end of this ArrayList • With generics, the objmust be of the correct type, or you get a compile-time (syntax) error • Always returns true • This is for consistency with other, similar classes • void add(intindex, Object element) • Inserts the element at position index in this ArrayList • The index must be greater than or equal to zero and less than or equal to the number of elements in the ArrayList • With generics, the objmust be of the correct type, or you get a compile-time (syntax) error

  17. Removing elements • boolean remove(Object obj) • Removes the first occurrence of obj from this ArrayList • Returns true if an element was removed • Uses equals to test if it has found the correct element • void remove(int index) • Removes the element at position index from this ArrayList • void clear() • Removes all elements

  18. Accessing with and without generics • Object get(int index) • Returns the component at position index • Using get the old way: • ArrayList myList = new ArrayList();myList.add("Some string");String s = (String)myList.get(0); • Using get the new way: • ArrayList<String> myList = new ArrayList<String>();myList.add("Some string");String s = myList.get(0); • Notice that casting is no longer necessary when we retrieve an element from a “genericized” ArrayList

  19. Searching a ArrayList • boolean contains(Object element) • Tests if elementis a component of this ArrayList • Uses equals to test if it has found the correct element • int indexOf(Object element) • Returns the index of the first occurrence of elementin this ArrayList • Uses equals to test if it has found the correct element • Returns -1 if elementwas not found in this ArrayList • int lastIndexOf(Object element) • Returns the index of the last occurrence of elementin this ArrayList • Uses equals to test if it has found the correct element • Returns -1 if elementwas not found in this ArrayList

  20. Getting information • boolean isEmpty() • Returns true if this ArrayList has no elements • int size() • Returns the number of elements currently in this ArrayList • Object[ ] toArray() • Returns an array containing all the elements of this ArrayList in the correct order

  21. More about equals • There are many different notions of equality • Example: two sets are equal if they contain the same elements; order of elements is irrelevant • Java defines public boolean equals(Object) in the Object class, but • equals is defined to be the same as == • It’s often a good idea to override equals for your own objects • If you do this, note that the argument should be a general Object • The String class (and some others) override equals

  22. Conclusion • A ArrayList is like an array of Objects • The advantage of a ArrayList is that you don’t need to know beforehand how big to make it • The disadvantage of a ArrayList is that you can’t use the special syntax for arrays • You should never use an array that you hope is “big enough”—use a ArrayList instead

More Related