ArrayLists and Collections Flashcards
What are some disadvantages of partially filled arrays?
- you must pass around two references (object and size)
- the limited size can cause problems
- Elements must be shifted left or right often
What are some disadvantages of the ArrayList class?
they can only hold Objects, not primitive types. To get around this, we use Integer, Double, Boolean, etc.
There is internal complexity and a speed penalty. Usually this is OK, but in computationally intensive tasks, ordinary arrays are preferred
What are wrapper classes?
Classes that represent primitive types as objects (Integer, Double, Boolean, etc.)
They store references to immutable objects (just like String)
Java will convert freely between primitive types and their wrapper type
How can you add things to an ArrayList?
a.add(“testing”) adds to the end
when 0 <= c <= a.size()
a.add(c, “testing”) inserts at c
a.set(c, “new”) replaces the item at c
when c < 0 or c > a.size()
a.add(c, “testing”), a.set(c, “new”)
gives an IndexOutOfBoundsException
add returns a boolean result meaning “did it change?”
set returns the old value that was deleted
How can you remove things from an ArrayList
when 0 <= c < a.size
a.remove(c) removes the element at index 0 and returns the deleted element
when c < 0 or c >= a.size
a.remove(c) gives an IndexOutOfBoundsException
a.remove(“testing”) removes that String, returns a boolean (“was it there?”)
a.clear() makes a empty
How do you search for something in ArrayLists?
int indexOf(Object)
int lastIndexOf(Object)
both of these methods use .equals() to determine equality
boolean contains(Object)
What is an alias?
An alias is a reference to the same object as another variable. Any changes to one of them will affect the other
How can you do a deep copy of an array?
a2 = new int[a1.length];
System.arrayCopy(a1, 0, a2, 0, a1.length);
However, if you need a true deep copy of an array of mutable objects, you should make clones at two different levels. In this case, writing your own loop is better
What does “garbage collection” do?
Frees up memory by deleting objects that have n places where the reference is stored (orphans)
What is a collection class?
A class whose primary role is to store a bunch of other objects. Simply using arrays of objects can make your main class very full; delegating the handling of the specifics of your objects to a collection makes this more useful. It makes your code reusable and encapsulation