Objects with ArrayLists as Attributes

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Chapter 5 Arrays and Vectors An array allows you to group data items together in a structure that is processed via an index. They allow you to process.
Writing a Class (defining a data-type). Create a new project : Project (uncheck the “Create Main Class”)
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 8, page 1 Sun Certified Java 1.4 Programmer Chapter 8 Notes Gary Lance
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Arrays of Objects 1 Fall 2012 CS2302: Programming Principles.
CSC 205 Programming II Lecture 18 The Eight Queens Problem.
The Java Collections Framework By the end of this lecture you should be able to: use the ArrayList class to store a list of objects; use the HashSet class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Object-Oriented Programming Simple Stack Implementation.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Exercise 2 Introduction to C# CIS Create a class called Employee that contains the following private instance variables: Social Securitystring.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
1.Reading from Keyboard 2.Main programs 3.Responsibilities 1 CS12230 Introduction to Programming Lecture 2or3-Other things.
Sit-In Lab 2 - OOP Restaurant.  Manage a restaurant and perform these types of queries: Assign a favorite table to a specific group Assign the lexicographically-smallest.
Announcements Final Exam: TBD. Static Variables and Methods static means “in class” methods and variables static variable: one per class (not one per.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Chapter 8 Arrays and the ArrayList Class Arrays of Objects.
More on Arrays Review of Arrays of ints, doubles, chars
The need for Programming Languages
[ 4.00 ] [ Today’s Date ] [ Instructor Name ]
Software Development Java Classes and Methods
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Chapter-7 part3 Arrays Two-Dimensional Arrays The ArrayList Class.
SELECTION STATEMENTS (1)
Continuing Chapter 11 Inheritance and Polymorphism
CS Week 14 Jim Williams, PhD.
Top Ten Words that Almost Rhyme with “Peas”
CS 302 Week 11 Jim Williams, PhD.
CS 302 Week 10 Jim Williams.
The ArrayList Class An ArrayList is a complex data structure that allows you to add or remove objects from a list and it changes size automatically. The.
An Introduction to Java – Part I, language basics
Interfaces and Constructors
Chapter 8 Slides from GaddisText
CSE 1030: Implementing Non-Static Features
ArrayList Collections.
Assignment 7 User Defined Classes Part 2
Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Chapter 6 Array-Based Lists.
slides created by Ethan Apter
Code Refresher Test #1 Topics:
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
CS 200 Objects and ArrayList
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
CIS 199 Final Review.
Java Programming with BlueJ Objectives
CSE 143 Lecture 2 ArrayIntList, binary search
Comparing Python and Java
Web Design & Development Lecture 6
Midterm 2 Review Lecture 23.
Methods/Functions.
A+ Computer Science AP Review 2019 AP CS A EXAM
Switch, Strings, and ArrayLists in Java
CS 200 Objects and ArrayList
ArrayLists Readings: 10.1 (pg. 559 – 571).
Midterm 2 Review Lecture 23.
Presentation transcript:

Objects with ArrayLists as Attributes CS102 Written by Robert Carver Edited by Dean Zeller

Objects can have attributes of almost any datatype Objects can have attributes of almost any datatype. This includes Arrays and ArrayLists. When an object has a list as an attribute, the contents of that list can only be accessed through object methods. Objects and Lists

Example of an Object with a List as an Attribute: 1 import java.util.*; 2 public class RecipeTest 3 { 4 public static void main(String[] args) 5 { 6 // Instantiate the list. Then fill the list with values. 7 List<String> ingredients = new ArrayList<String>(); 8 ingredients.add("Eggs"); 9 ingredients.add("Flower"); 10 ingredients.add("Sugar"); 11 12 Recipe cake = new Recipe(ingredients); 13 14 cake.addIngredient("Sprinkles"); 15 cake.removeIngredient("Flower"); 16 cake.searchIngredient("Beef"); 17 System.out.println(cake); 18 } 19 } Output: Flower has been removed from the list. Beef is not in the ingredient list. Ingredients: Eggs Sugar Sprinkles

Object code: Breakdown on following slides 1 import java.util.*; 2 public class Recipe 3 { 4 // Variables and constructor 5 private List<String> ingredients; 6 // No parameter constructor 7 public Recipe() 8 { 9 this.ingredients = new ArrayList<String>(); 10 } 11 // Constructor with parameter 12 public Recipe(List<String> ingredients_) 13 { 14 for(int i = 0; i < ingredients_.size(); i++) 15 ingredients.add(ingredients_.get(i)); 17 } 18 // Add item to list 19 public void addIngredient(String ingredient_) 20 { 21 ingredients.add(ingredient_); 22 } 23 // Remove item from list 24 public Boolean removeIngredient(String toRemove_) 25 { 26 if(ingredients.contains(toRemove_)) 27 { 28 ingredients.remove(ingredients.indexOf(toRemove_)); 29 return true; 30 } 31 else return false; 32 } 33 // search for item within list 34 public Boolean searchIngredient(String target_) 35 { 36 if(ingredients.contains(target_)) 37 { 38 return true; 39 } 40 else return false; 41 } 42 // toString method for food object 43 public String toString() 44 { 45 String result="Ingredients: \n"; 46 for(int i = 0; i < ingredients.size(); i++) 47 result+=(ingredients.get(i)+"\n"); 48 return result; 49 } 50 } Object code: Breakdown on following slides

Constructors Constructors for objects can assign all, some, or none of the attributes of an object. The objects attributes must be assigned before they are accessed otherwise Java will run into an error. Constructor with no parameters 7 public Recipe() 8 { 9 this.ingredients = new ArrayList<String>(); 10 } 12 public Recipe(List<String> ingredients_) 13 { 14 for(int i = 0; i < ingredients_.size(); i++) 15 ingredients.add(ingredients_.get(i)); 17 } Constructor with parameters

Code breakdown - constructors 1 import java.util.*; 2 public class Recipe 3 { 4 // Variables and constructor 5 private List<String> ingredients; 6 // No parameter constructor 7 public Recipe() 8 { 9 this.ingredients = new ArrayList<String>(); 10 } 11 // Constructor with parameter 12 public Recipe(List<String> ingredients_) 13 { 14 for(int i = 0; i < ingredients_.size(); i++) 15 ingredients.add(ingredients_.get(i)); 17 } We initialize the class with a single attribute: a ArrayList of strings called ingredients. We then create the constructor that accepts a List<String> parameter to be passed into the object. And also another constructor that includes no parameters.

Code breakdown – add method // Add item to list 18 public void addIngredient(String ingredient_) 19 { 20 ingredients.add(ingredient_); 21 } We create a public void method called addIngredient. We pass a String parameter into this method. The method then adds the String into the ingredients list.

Code breakdown – remove method // Remove item from list 23 public Boolean removeIngredient(String toRemove_) 24 { 25 if(ingredients.contains(toRemove_)) 26 { 27 ingredients.remove(ingredients.indexOf(toRemove_)); 28 return true; 29 } 30 else return false; 31 } We create another public Boolean method called removeIngredients. We pass a String parameter into this method. The method first calls the .contains method of the ArrayList class on the String to check if the ingredients list contains the toRemove_ String. If the list contains the String the method removes the String using the .remove and .indexOf methods and returns true. If the list does not contain the String, the method returns false.

Code breakdown – search method // search for item within list 33 public Boolean searchIngredient(String target_) 34 { 35 if(ingredients.contains(target_)) 36 { 37 return true; 38 } 39 else return false; 40 } We create another public Boolean method called searchIngredients. We pass a String parameter, target_ into this method. The method does a .contains test, if the ingredients list contains target_ then return true. If the ingredients list does not contain target_ then return false.

Code breakdown – toString method // toString method for food object 42 public String toString() 43 { 44 String result="Ingredients: \n"; 45 for(int i = 0; i < ingredients.size(); i++) 46 result+=(ingredients.get(i)+"\n"); 47 return result; 48 } We create a public String method toString that we pass no parameters into. The method creates a String and then iterates through the ingredients list using a For loop, appending each item in the list to the String. Example Output: Ingredients: Eggs Sugar Sprinkles