Comprehensive Guide to Java ArrayList Class
60 likes | 80 Vues
Learn about Java ArrayList class, its properties, constructors, main methods, and how to effectively use it to store and manage collections of elements in Java programming.
Comprehensive Guide to Java ArrayList Class
E N D
Presentation Transcript
Programming II (CS300)Chapter 02: Using ObjectsJava ArrayList Class Mouna KACEM mouna@cs.wisc.edu Spring 2019
Java ArrayList Class Iterable extends • Java ArrayList Class inJava.utilpackage • uses a dynamic array for storing a set of elements • inherits AbstractList class and implements List interface • Main Properties • Java ArrayList class can contain duplicate elements • Java ArrayList class maintains insertion order • Java ArrayList allows random access • The dynamic array works at the index basis Collection extends List implements AbstractList extends ArrayList https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
Java ArrayList Class • Constructors • ArrayList list1 = new ArrayList(); //creating an empty ArrayList • ArrayList<String> list2 = new ArrayList<String>(); //creating an empty ArrayList of elements of type String • the type of elements is specified in angular braces • ArrayList list2 is forced to have only specified type of objects in it (here String). • Adding another type of object, results in a compile time error • ArrayList(Collection c) • build an array list that is initialized with the elements of the collection c. • ArrayList(int capacity) • build an array list that has the specified initial capacity.
Java ArrayList Class • Main Methods (1) • boolean add(Object o) • used to append the specified element to the end of a list. • void add(int index, Object element) • insert the specified element at the specified position index in a list. • booleanaddAll(Collection c) • append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. • booleanaddAll(int index, Collection c) • used to insert all of the elements in the specified collection into this list, starting at the specified position.
Java ArrayList Class • Main Methods (2) • intindexOf(Object o) • used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. • intlastIndexOf(Object o) • return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Java ArrayList Class • Main Methods(3) • void clear() • remove all of the elements from this list. • Object[] toArray() • used to return an array containing all of the elements in this list in the correct order. • Object clone() • used to return a shallow copy of an ArrayList.