Converting Collections to Arrays. A Bad Approach to Array Conversion. A Better Approach to Array Conversion. public Object[] toarray();

Similar documents
Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Searching for Information. A Simple Method for Searching. Simple Searching. Class #21: Searching/Sorting I

CMSC 341. Linked Lists. Textbook Section 3.5

Review: Using Imported Code. What About the DrawingGizmo? Review: Classes and Object Instances. DrawingGizmo pencil; pencil = new DrawingGizmo();

Review: Classes and Object Instances. Review: Creating an Object. Using Multiple Objects. DrawingGizmo pencil; pencil = new DrawingGizmo();

CS231 - Spring 2017 Linked Lists. ArrayList is an implementation of List based on arrays. LinkedList is an implementation of List based on nodes.

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

Announcements. CS18000: Problem Solving And Object-Oriented Programming

Data structure is an organization of information, usually in memory, for better algorithm efficiency.

package weiss.util; // Fig , pg // Fig 6.16,6.17, pg package weiss.util;

CS 3 Introduction to Software Engineering. 5: Iterators

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/30/03 Lecture 7 1

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/22/04 Lecture 4 1

LINKED LISTS cs2420 Introduction to Algorithms and Data Structures Spring 2015

Basic Class Diagrams. Class Diagrams, cont d. Class Diagrams, cont d. Car. Car. Car. What does the minus sign here mean?

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

CS 61B Data Structures and Programming Methodology. June David Sun

Computer Science 210 Data Structures Siena College Fall 2018

In this lecture Simple List Algorithms

CS32 Discussion Week 3

Programming II (CS300)

Goal. Generic Programming and Inner classes. Minor rewrite of linear search. Obvious linear search code. Intuitive idea of generic linear search

Introduction to Programming Using Java (98-388)

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

CS Introduction to Data Structures Week 1 Thursday

Linked Lists

Homework #10 due Monday, April 16, 10:00 PM

CS 180 Final Exam Review 12/(11, 12)/08

Announcements/Follow-ups

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

Linked List Nodes (reminder)

Java Collection Framework

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

Cloning Enums. Cloning and Enums BIU OOP

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList!

Programming II (CS300)

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

CS : Data Structures Michael Schatz. Sept Lecture 5: Iterators

Object Oriented Software Design

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

List ADT. Announcements. The List interface. Implementing the List ADT

JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015

CS 151. Exceptions & Javadoc. slides available on course website. Sunday, September 9, 12

CS 101 Fall 2006 Midterm 1 Name: ID:

CmpSci 187: Programming with Data Structures Spring 2015

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

Array. Prepared By - Rifat Shahriyar

Welcome to CSL 201 Data Structures

CS 310: Array-y vs Linky Lists

CS61B Lecture #5: Arrays and Objects

EECS 2011 M: Fundamentals of Data Structures

Arrays. Array Definition

CS 61B Discussion 5: Inheritance II Fall 2014

Lab 5 Random numbers!

Week 2. TA Lab Consulting - See schedule (cs400 home pages) Peer Mentoring available - Friday 8am-12pm, 12:15-1:30pm in 1289CS

CS : Data Structures

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1

CS 231 Data Structures and Algorithms, Fall 2016

Arrays. myints = new int[15];

Please note that if you write the mid term in pencil, you will not be allowed to submit a remark request.

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Last time s big ideas

CSE443 Compilers. Dr. Carl Alphonce 343 Davis Hall

Programming Exercise 14: Inheritance and Polymorphism

ArrayList. Introduction. java.util.arraylist

CS18000: Problem Solving And Object-Oriented Programming

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

An Activation Record for Simple Subprograms. Activation Record for a Language with Stack-Dynamic Local Variables

COS 126 Exam Review. Exams overview Example programming exam Example written exam questions (part 1)

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

CS/ENGRD 2110 SPRING 2018

Announcements. Java Graphics. Exceptions. Java Odds & Ends

MIDTERM EXAM THURSDAY MARCH

H212 Introduction to Software Systems Honors

CS61BL. Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

Lab Assignment Three

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Computer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Java Review: Objects

CS171 Midterm Exam. October 29, Name:

CSE 143. Lecture 7: Linked List Basics reading: 16.2

Winter 2016 COMP-250: Introduction to Computer Science. Lecture 6, January 28, 2016

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

An Introduction to Data Structures

Computer Science II CSci 1200 Sections 1-4,6 Week 6, Friday Class October 5, 2001 Linked Lists, Part 2

EECE.2160: ECE Application Programming

CS 61B Data Structures and Programming Methodology. July 2, 2008 David Sun

January 24, Abstract Data Types (ADTs) An ADT is an abstraction of a data structure.

Announcements. 1. Forms to return today after class:

Transcription:

Converting Collections to Arrays Every Java collection can be converted to an array This is part of the basic Collection<T> interface The most elementary form of this method produces an array of base-type (java.lang.object): Class #12: Converting Collections to Arrays; Linked Lists public Object[] toarray(); This method can be quite simple, although there are some complications to which we must pay attention Software Design III (CS 340): M. Allen, 19 Feb. 19 Tuesday, 19 Feb. 2019 Software Design III (CS 340) 2 A Bad Approach to Array Conversion The simplest approach to such a method, for something like an ArrayList, is actually a bad idea public Object[] toarray() return theitems; This seemingly simple approach essentially makes the array contained by the list object a public entity After running this method, other classes would be able to directly access the array, adding data wherever desired, including in places that are outside of the bounds given by the size() of the list This goes against the whole idea of encapsulating data as private members of a class A Better Approach to Array Conversion Instead of direct access to the contained array, a better approach is to create a new one, and copy over public Object[] toarray() Object[] copy = new Object[theSize]; for (int i = 0; i < thesize; i++) copy[i] = theitems[i]; return copy; Tuesday, 19 Feb. 2019 Software Design III (CS 340) 3 Tuesday, 19 Feb. 2019 Software Design III (CS 340) 4 1

Important: Java Copies are Shallow A method like the one just shown creates a brand-new array At the same time, the items inside the array are not new This is default Java Collection behavior: copies and array conversions are always shallow copies: changes made to such items will change the objects in both collections in which they are referenced ArrayList<JFrame> framelist = new ArrayList<>(); for (int i = 0; i < 5; i++) framelist.add(new JFrame("Old Title")); System.out.println(frameList.get(0).getTitle()); Object[] framearray = framelist.toarray(); ((JFrame) framearray[0]).settitle("new Title"); System.out.println(frameList.get(0).getTitle()); Old Title New Title (Changing in array also changes in list) Complication: Generic Arrays Cannot Be Instantiated Suppose we want to convert a generic ArrayList<T> to an array of the same type: public T[] toarray() T[] array; array = new T[theSize]; for (int i = 0; i < thesize; i++) array[i] = theitems[i]; return array; This won t compile! While we can declare the array to have generic type, we cannot instantiate it: we are required to give it an actual type first error: Cannot create a generic array of T Tuesday, 19 Feb. 2019 Software Design III (CS 340) 5 Tuesday, 19 Feb. 2019 Software Design III (CS 340) 6 Getting around the Generic Array Issue To set the return type, we need to supply something that is guaranteed to have a non-generic specified type: import java.lang.reflect.array;... We can use Java s ability to do reflection to create a new array of the same class-type as the input array (works even if empty) public T[] toarray(t[] a) T[] array = (T[]) Array.newInstance(a.getClass().getComponentType(), size()); Getting Around the Generic Array Issue The reason to include the input array, rather than just get the type of the list data itself is that we can use the input array to provide type-checking at the calling site: MyArrayList<Integer> lsti = new MyArrayList<Integer>(); MyArrayList<Double> lstd = new MyArrayList<Double>(); Integer[] ints = lsti.toarray(new Integer[0]); Double[] dubs = lstd.toarray(new Double[lstd.size()] ); for (int i = 0; i < size(); i++) array[i] = theitems[i]; return array; Since newinstance() returns an Object, we must cast to T[] getclass(): from java.lang.object getcomponenttype(): from java.lang.class (used specifically to get type of an array element) Since the array typing and casting occurs inside of toarray() method, we can be certain that, if the method completes, we have actual (non-erased) arrays of the given types (Integer or Double) While we can convert even with an empty array, there turns out to be a reason to use the second version of this sort of call in most cases. Tuesday, 19 Feb. 2019 Software Design III (CS 340) 7 Tuesday, 19 Feb. 2019 Software Design III (CS 340) 8 2

A Small Efficiency All else being equal, we will prefer: Double[] dubs = lstd.toarray(new Double[lstd.size()] ); This turns out to save on object typing, creation and casting, and can run significantly faster overall. The Linked List ADT head: public T[] toarray(t[] a) if (a.length >= size()) for (int i = 0; i < size(); i++) a[i] = theitems[i]; if (a.length > size()) a[size()] = null; return a; // code to create new array if needed... If we can fit the current list into the input array, then simply copy over without need for typing, array creation, casting. If input array larger than needed, set element at end of list-data to null. Warning: this will be a problem when list could contain null items itself, so we always prefer to use size of list for input array if at all possible. Tuesday, 19 Feb. 2019 Software Design III (CS 340) 9 General idea: an implementation of List interface/adt, using a set of linked nodes, with size() == # nodes Each node two basic attributes: Data: object that it stores (simple or complex) Next link: a variable reference to the next node in list End of list links to null object (can be used as a marker) Tuesday, 19 Feb. 2019 Software Design III (CS 340) 10 Doubly Linked Lists head: Actual java.util. class is slightly more complex, since each node has two separate links A bi-directional, doubly-linked list s link to both the next and previous nodes in list order Front: prev links to null object Back: next links to null object Tuesday, 19 Feb. 2019 Software Design III (CS 340) 11 One Last Complication: Sentinel s :head tail: For convenience, implementations will use one/more sentinel nodes These track the start (head) or end (tail) of the list (and have no data) Can make code easier to write, but don t generally change basic behavior Tuesday, 19 Feb. 2019 Software Design III (CS 340) 12 3

s private static class <T> private T data; private <T> prev; private <T> next; public ( T d, <T> p, <T> n ) data = d; prev = p; next = n; Basic data component of list is a nested, private static class Packaged inside list class itself private to that class, so it cannot be created anywhere else by itself It carries the type of the list class instance, <T> Making the class static separates it from the parent class, so it has no requirement for a linked instance of the parent to exist This simplifies things, and can improve memory management This is a good approach, so long as the nested class doesn t need direct access to other nonstatic members (variables, methods) of the containing class Containing List class does have direct access to elements, whether is static or not Creating the public class My<T> implements Iterable<T> private int thesize; private <T> head; private <T> tail; public My() clear(); public void clear() head = new <T>( null, null, null ); tail = new <T>( null, head, null ); head.next = tail; thesize = 0; Use head/tail nodes to indicate start/end of list Can access private next and prev link variables in directly, since it is a nested member class, contained entirely inside the List class itself. Tuesday, 19 Feb. 2019 Software Design III (CS 340) 13 Tuesday, 19 Feb. 2019 Software Design III (CS 340) 14 Creating the prev: :head tail: size: 0 head = new <T>( null, null, null ); tail = new <T>( null, head, null ); head.next = tail; Iterators private class Iterator implements java.util.iterator<t> private <T> current = head.next; public boolean hasnext() return current!= tail; public T next() if(!hasnext() ) throw new java.util.nosuchelementexception(); T nextitem = current.data; current = current.next; return nextitem; public void remove() My.this.remove( current.prev ); This private inner class is not static It can easily directly access any other elements of the List class it needs. Use the head/tail nodes as indicators of the start/end of the list Use the next/prev variable references to navigate from node to node in the list. Tuesday, 19 Feb. 2019 Software Design III (CS 340) 15 Tuesday, 19 Feb. 2019 Software Design III (CS 340) 16 4

This Week Topic: Lists Read: Text, chapter 03 Meetings: as usual Monday Wednesday: 2205 Centennial Friday: Lab, 16/17 Wing Homework 02: due Friday, 01 March (5:00 PM) Office Hours: Wing 210 Monday: 9:00 AM 10:30 AM Tuesday: 3:00 PM 4:00 PM Wednesday: 9:00 AM 10:30 AM Thursday: 2:00 PM 3:00 PM Friday: 9:00 AM 10:30 AM Tuesday, 19 Feb. 2019 Software Design III (CS 340) 17 5