70 likes | 80 Vues
Explore class hierarchies, ArrayList, and Linked List in Java. Understand methods, operations, and iterators for better coding. Enhance your skills with practical examples.
E N D
Announcements Lab 9: Inheritance Defining & using class hiearchies Read: R&S 11 Last Time: Collections ArrayList - look up - constant time remove, resizing, insert in the middle - expensive, time proportional to the list size Today: a new collection Linked List - similar operations as ArrayList, but different storage model resizing, removal, insertion - constant time find - proportional to list size. Announcements & Review Lecture 30: Collections Linked List
Linked List Storage Model start end null next prev Key: node • No diriect indexing, as in arrays, so you must iterate over the list to enumerate an element • Adding at the front or the back is constant time, i.e., resizing is cheap Lecture 30: Collections Linked List
InterestingLinkedList<E> Methods • size() - returns number of objects • add(Object o) - adds at end of list • get(int i) - returns ith object in the list • set(int i, Object o) - stores o at ith position in list • add(int i, Object o) - adds o at ith position, shifts other objects to the right • E remove() - removes and returns element current position, shifts elements to the left • removeFirst(), removeLast(), remove(E v), remove(int i), remove() Lecture 30: Collections Linked List
InterestingLinkedList<E> Methods • E clone() - return a shallow copy of the list • Boolean addAll(LinkedList<E> c) - add collection c to end of list, return true if list changes • E peek() - return the first element without removing it from the list • Boolean hasNext(), E next() - iteration Lecture 30: Collections Linked List
Linked List apples null 33 41 8 101 14 McIntosh Red Gala Fuji Golden Delicious • Linked list example declaration (same as ArrayList): • LinkedList<Items> apples = new LinkedList<Items>(); • Items a = new Items(“McIntosh”, 33); • apples.add(a); • a = new Items(“Red”, 41); • apples.add(a); ... Lecture 30: Collections Linked List
Iterators for LinkedList // Basic format: Iterator<E> itr = list.iterator(); while (itr.hasNext()) { E element = itr.next(); // do something with the object } // Example: Delete “Gala” apples inventory LinkedList<Items> apples = new LinkedList<Items>(); ... Iterator<Items> i = apples.iterator(); while (i.hasNext()) { Items item = i.next(); if (item.getName().equals(“Gala”)) { i.remove(); } } Lecture 30: Collections Linked List
BlueJ Lecture 30: Collections Linked List