Comp103 Assignment 47

Presentation on theme: "Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The ArrayList Class How to Create an ArrayList Object Adding Elements to."— Presentation transcript:

1 Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The ArrayList Class How to Create an ArrayList Object Adding Elements to an ArrayList Object How to Access an Element Within an ArrayList How to Update an ArrayList Object Additional ArrayList Methods Printing or Concatenating an ArrayList Storing Primitives in an ArrayList ArrayList Example Using Anonymous Objects and a For-Each Loop ArrayList Objects Versus Standard Arrays 1

2 Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The LinkedList Class The List Interface Comparing Method Execution Times Queues, Stacks, and the ArrayDeque Class Overview of the Java Collections Framework Collections Example – Information Flow in a Network of Friends 2

3 The ArrayList Class The ArrayList class provides the basic functionality that comes with a standard array, plus it provides additional functionality. The basic functionality: An ArrayList stores an ordered collection of values and allows access to the values via an index. The added functionality: An ArrayList grows and shrinks dynamically by inserting and deleting elements at any specified location. 3

4 How to Create an ArrayList Object The ArrayList class is defined in the Java API's java.util package, so for files that use the ArrayList class, import it like this: import java.util.ArrayList; To initialize an ArrayList reference variable, in a declaration, use this syntax: ArrayList reference-variable = new ArrayList<>(); For example, here's how to initialize an ArrayList reference variable named students : ArrayList students = new ArrayList<>(); Use angled brackets to surround the type for the elements, and the type must be a class name (not a primitive). Use empty angled brackets (the diamond operator). 4

5 How to Create an ArrayList Object Let's compare the syntaxes for creating ArrayList objects, regular objects, and standard arrays. Here's the same ArrayList example as before: ArrayList students = new ArrayList<>(); Here's an object example: Mouse gus = new Mouse(); Here's a standard-array example: Student[] students = new Student[100]; 5

6 Adding Elements to an ArrayList Object To add an element to the end of an ArrayList object, use this syntax: ArrayList-reference-variable.add( item ); The item that's added must be the same type as the type specified in the ArrayList 's declaration. Write a code fragment that creates this ArrayList object: computerScientists 0"Ada Lovelace" 1"Grace Hopper" 2"Marissa Mayer" 6

7 Java API API stands for application programming interface. The Java API is the interface to the huge library of pre-built Java classes. As a programmer, you don't need to know the internals of those classes; you just need to know how to use them. Or said another way, you just need to know how to interface with them. To interface with them, you need to use their public methods. To use a method, you need to know what type of argument(s) to pass to it and what type of value it returns. A method's API shows the method's parameters and its return type. The standard way to show that information is to show the method's heading. For example, here's the API heading for the Math class's pow method: public static double pow(double num, double power) 7

8 How to Access an Element Within an ArrayList With standard arrays, you use square brackets to access and update an element. ArrayList objects don't use square brackets. Instead, they use a get method to access an element and a set method to update an element. Here's the API heading for the ArrayList 's get method: public E get(int index) Semantics: The index parameter specifies the position of the desired element within the ArrayList calling object. As with standard arrays, the first element is at position 0, the second element is at position 1, etc. If index refers to a nonexistent element, then a runtime error occurs. If index is valid, then get returns the element at the specified position. 8

9 How to Access an Element Within an ArrayList Note the E return type for the ArrayList 's get method: public E get(int index) The E stands for element. It represents the data type of the ArrayList 's elements. It's the same as the element-type specified in the ArrayList 's initialization: ArrayList reference-variable = new ArrayList<>(); 9

10 How to Update an ArrayList Object The set method allows you to assign a value to an existing ArrayList element. Here's its API heading: public E set(int index, E elem) Semantics: The index parameter specifies the position of the element you're interested in. If index refers to a nonexistent element, then a runtime error occurs. If index is valid, then set assigns the elem parameter to the specified element, overlaying whatever was there originally. E represents the data type of the ArrayList 's elements. 10

11 How to Update an ArrayList Object Draw a picture of the colors ArrayList after this code fragment executes: String mixedColor; ArrayList colors = new ArrayList<>(); colors.add("red"); colors.add("green"); colors.add("blue"); mixedColor = colors.get(0) + colors.get(1); colors.set(2, mixedColor); 11

12 Additional ArrayList Methods public void add(int index, E elem) Starting with the specified index position, shift the original elements to higher-indexed positions. Then insert the elem parameter at the specified index position. public void clear() Remove all elements from the list. public int indexOf(Object elem) Search for the first occurrence of the elem parameter within the list. If it's found, return its index position. If it's not found, return -1. public boolean isEmpty() Return true if the list contains no elements. public E remove(int index) Remove the element at the specified index position, shift all higher-indexed elements to lower-indexed positions, and return the removed element. public int size() Return the number of elements in the list. Object is a generic class that can be used as a class type for any object. 12

13 Example ArrayList Program import java.util.ArrayList; public class HungerGames { public static void main(String[] args) { int deceasedIndex; // index of deceased tribute String deceased; // name of deceased tribute ArrayList tributes = new ArrayList<>(); tributes.add("Cato"); tributes.add("Katniss"); tributes.add("Peeta"); tributes.add("Rue"); tributes.add(1, "Finnick"); deceasedIndex = (int) (Math.random() * tributes.size()); deceased = tributes.remove(deceasedIndex); System.out.println(deceased + " is no longer in the game."); System.out.println("Remaining: " + tributes); } // end main } // end HungerGames 14

14 Printing or Concatenating an ArrayList If you attempt to print or concatenate an ArrayList, the ArrayList returns a comma-separated list of ArrayList elements surrounded by square brackets, []. For example, in the HungerGames program, if Peeta is removed, the last line prints this: Remaining: [Cato, Finnick, Katniss, Rue] 15

15 Storing Primitives in an ArrayList As mentioned previously, ArrayList s store references. For example, in the HungerGames program, tribe is an ArrayList of strings, and strings are reference types. If you need to store primitives in an ArrayList, you can't do it directly, but you can do it if the primitives are wrapped in wrapper classes. Ever since Java 5.0, the "wrapping" process has been done behind the scenes. For ArrayList s, it's done automatically if a wrapper class is used in an ArrayList declaration. The StockAverage program on the next slide reads int stock values and stores them in an ArrayList. After all stock values are entered, the program calculates the average stock value. Why is an ArrayList appropriate for calculating a stock average? 16

16 Storing Primitives in an ArrayList import java.util.Scanner; import java.util.ArrayList; public class StockAverage { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); ArrayList stocks = new ArrayList<>(); double stock; // a stock value double stockSum = 0; // sum of stock values System.out.print("Enter a stock value (-1 to quit): "); stock = stdIn.nextDouble(); while (stock >= 0) { stocks.add(stock); System.out.print("Enter a stock value (-1 to quit): "); stock = stdIn.nextDouble(); } // end while Must be a wrapper class, not a primitive. Automatic boxing (“autoboxing”) takes place here. 17

17 Storing Primitives in an ArrayList for (int i=0; i

18 ArrayList Example Using Anonymous Objects and a For-Each Loop When storing objects in an ArrayList, it's common to create an object and add it to the ArrayList all in the same statement. For example, the upcoming BearStore program stores Bear objects in an ArrayList. In storing a Bear object, the program creates a Bear object and adds it to the bears ArrayList, all in the same statement: bears.add(new Bear("Acme", "brown teddy")); An anonymous object is an object that's instantiated, but it's not stored in a variable (and with no variable, there's no name for it; thus, we say it's "anonymous"). 19

19 ArrayList Example Using Anonymous Objects and a For-Each Loop import java.util.Scanner; import java.util.ArrayList; public class BearStore { ArrayList bears = new ArrayList<>(); //********************************************************** // Fill store with specified number of standard teddy bears. public void addStdBears(int num) { for (int i=0; i

20 ArrayList Example Using Anonymous Objects and a For-Each Loop //********************************************************** // Fill store with specified number of customized bears. public void addUserSpecifiedBears(int num) { for (int i=0; i

21 ArrayList Example Using Anonymous Objects and a For-Each Loop //********************************************************** // Print all the bears in the store. public void displayInventory() { for (Bear bear : bears) { bear.display(); } } // end displayInventory //********************************************************** public static void main(String[] args) { BearStore store = new BearStore(); store.addStdBears(3); store.addUserSpecifiedBears(2); store.displayInventory(); } // end main } // end BearStore class 22

22 ArrayList Example Using Anonymous Objects and a For-Each Loop public class Bear { private final String MAKER; // bear's manufacturer private final String TYPE; // type of bear //********************************************************** public Bear(String maker, String type) { MAKER = maker; TYPE = type; } public void display() { System.out.println(MAKER + " " + TYPE); } } // end Bear class 23

23 Anonymous Objects The bear store program contains several examples of using anonymous objects. In general, you'll see anonymous objects being used in two circumstances: Passing a newly created object into a method or constructor. For example: bears.add(new Bear("Acme", "brown teddy")); Returning a newly created object from a method. For example: return new Bear(maker, type); 24

24 For-Each Loop Note the for-each loop in the BearStore' s displayInventory method: public void displayInventory() { for (Bear bear : bears) { bear.display(); } } // end displayInventory For-each loop syntax for an ArrayList : for ( : ) Read this as "for each bear in bears, …" For each iteration through the loop, bear accesses the next element in the bears ArrayList. 25

25 For-Each Loop Note that using the for-each loop is an option, not a requirement. Here's an alternative displayInventory implementation that uses a standard for loop: public void displayInventory() { for (int i=0; i

26 ArrayList Objects Versus Standard Arrays Benefits of an ArrayList Over a Standard Array Benefits of a Standard Array Over an ArrayList 1. It's easy to increase the size of an ArrayList – just call add. 1. A standard array uses []'s to access array elements (which is easier than using get and set methods). 2. It's easy for a programmer to insert or remove an element to or from the interior of an ArrayList – just call add or remove and specify the element's index position. 2. A standard array is more efficient with storing primitive values. 27

27 The LinkedList Class A linked list is like an ArrayList, in that in holds a collection of related data, but instead of using an underlying array to store the data, it uses a chain of references: 28

28 The List Interface ArrayList and LinkedList implement many of the same methods, like: get, set, add, remove, clear, and size. That’s because they both implement the same List interface. In Java API documentation, you’ll see: public class ArrayList implements List public class LinkedList implements List stand for element type. implements means the class promises to implement all methods specified by the interface. 29

29 The List Interface - continued In the past, you’ve declared variables with a primitive type or a class name at the left, like this: double distance; Student student; You can also declare a variable with an interface at the left, like this: List iPhoneApps; First, you could assign an ArrayList object to iPhoneApps. Then, later, you could assign a LinkedList object to the same variable: iPhoneApps = new ArrayList ;... iPhoneApps = new LinkedList ; The same List method call would do the same kind of thing with either type of collection, but of course, the detailed implementations would differ. 30

30 LinkedList vs. ArrayList Performance With a LinkedList, It’s easiest to find, add, or remove elements that are near one of the two ends. Once an element has been found, it’s easier to remove it from a LinkedList (change a pair of references) than from an ArrayList (shift all higher elements to lower array indices). However, finding an indexed element is much slower in a LinkedList than in an ArrayList, because: Instead of jumping right to the indexed position, the computer must step in from an end until the step count equals the index number (when starting at the head) or equals the length minus the index number (when starting at the tail). 31

31 Measuring Method Execution Time Measure the average time to get each element at a random index and then set each element at a different random index. Assume a getIndices(length) helper method returns an array of all integers between zero and length in a random sequence with no duplications. First do it for an ArrayList. Then do it for a LinkedList. public static void main(String[] args) { String operationType = "average get and set time"; int length = 1000; int[] indicesA = getIndices(length); int[] indicesB = getIndices(length); ArrayList list = new ArrayList<>(); Double element; long time0, time1; 32

32 A getIndices method (hidden) private static int[] getIndices (int length) { Random random = new Random(); ArrayList integers = new ArrayList<>(); int[] indices = new int[length]; for (int i=0; i

33 Measuring Method Execution Time // Populate the list for (int i=0; i

34 Comparing Method Access Times System.out.println(list.getClass()); System.out.printf("for length = %d, %s = %,d ns\n", length, operationType, (time1 - time0) / length); } // end main Output : class java.util.ArrayList for length = 1000, average get and set time = 174 ns Replace ArrayList by LinkedList and repeat, to obtain: Output: class java.util.LinkedList for length = 1000, average get and set time = 1,455 ns 35

35 Comparing Method Mutate Times Substitute: String operationType = "average remove and add time"; And replace the for loop body with this: element = list.remove(indicesA[i]); list.add(indicesB[i], element); Then the comparison generates results like these: Output : class java.util.ArrayList for length = 1000, average remove and add time = 1,082 ns Replace ArrayList by LinkedList and repeat, to obtain: Output: class java.util.LinkedList for length = 1000, average remove and add time = 2,543 ns 36

36 Queues After adding a, b, and then c: After a remove operation: After adding d: bcd front back abc front back b front c back A queue is a first-in first-out (FIFO) waiting line. We add elements to the back (tail), and we remove elements from the front (head). 37

37 Queues − continued Although we could implement a queue with a LinkedList or an ArrayList, Java’s ArrayDeque is more efficient. An ArrayDeque is backed by an array. The backing array’s length is initially 16, and its length doubles each time the current length is inadequate. The backing array is circular – links connect opposite ends. Pointers identify current head and tail elements. Adding increments tail pointer. Deleting increments head pointer. The ArrayDeque class implements the Deque (pronounced “deck”) interface. To access Java’s Deque interface and ArrayDeque class: import java.util.*; // for Queue and ArrayDeque 38

38 Restaurant Queue Example public static void main(String[] args) { String servedPerson; // from the queue's head Queue chipotlesQueue = new ArrayDeque<>(); chipotlesQueue.add("Alexa"); chipotlesQueue.add("Carolyn"); while (!chipotlesQueue.isEmpty()) { servedPerson = chipotlesQueue.remove(); System.out.println("What is your order, " + servedPerson + "?"); } } // end main 39

39 Stacks After pushing a, b, and then c: After a pop operation: After pushing d: c b a b a d b a top A stack is a last-in first-out (LIFO) storage container. We add (push) and remove (pop) elements at the top. 40

40 Driveway-Parking Stack Example /************************************************************* * DrivewayParking.java * Dean & Dean * * This program uses stacks to help a driveway parking service. *************************************************************/ import java.util.*; // ArrayDeque, Scanner public class DrivewayParking { private ArrayDeque driveway1 = new ArrayDeque<>(); private ArrayDeque driveway2 = new ArrayDeque<>(); //********************************************************* public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); char action; String licensePlate; DrivewayParking attendant = new DrivewayParking(); 41

41 Driveway-Parking Stack Example do { attendant.describeDriveways(); System.out.print("Enter +license to add, " + "-license to remove, or q to quit: "); licensePlate = stdIn.nextLine(); action = licensePlate.charAt(0); licensePlate = licensePlate.substring(1); switch (action) { case '+': attendant.parkCar(licensePlate); break; case '-': if (!attendant.getCar(licensePlate)) System.out.println("Sorry, couldn't find it."); } // end switch } while (action != 'q'); } // end main 42

42 Driveway-Parking Stack Example public void describeDriveways() { System.out.println("driveway1 " + driveway1); System.out.println("driveway2 " + driveway2); } // end describeDriveways() //********************************************************* // This method parks a car in the least full driveway. private void parkCar(String licensePlate) { if (driveway1.size() <= driveway2.size()) driveway1.push(licensePlate); else driveway2.push(licensePlate); } // end parkCar 43

HomeProgramsPeopleLaboratoriesAMESDownloadsAbout Us

| Designed by Anup KC and Maintained by Bijendra Shrestha | Copyright © Department of Mechanical Engineering, Kathmandu University, Dhulikhel, Nepal | 2015 | All rights reserved |

B.E. in Mechanical Engineering (Subdivision)

Bachelor of Engineering (B.E.) in Mechanical Engineering with subdivision is a four-year program spread over eight semesters. A student needs to complete 47 credit hours, of course work, project work and internship, for graduation.

B.E. in Mechanical Engineering with subdivision offers its general mechanical engineering courses with specialization courses and related activities in 4 different areas viz. Automobile, Design & Manufacturing, Energy Technology and Hydropower, so that the students will be graduating as a Mechanical Engineer with skill and proficiency in one of the 4 core areas. Out of 147 credit hours, about 80 % of the courses will be common to all the subdivisions while students under each subdivision will have 20 % of specialized courses through project work, elective courses and industrial training.

B.E. Subdivision Courses

Year

Semester

Theory

Lab

Project

First

I

PHYS 101

CHEM 101

MATH 101

ENGG 111

ENGT 101

COMP 103

EDRG 101

ENGG 101

II

ENGG 112

PHYS 102

MATH 104

COMP 116

ENVE 101

ENGT 102

EDRG 102

ENGG 102

Second

III

MATH 207

MEEG 217

MEEG 216

MEEG 213

EEEG 204

MEEG 219

MEEG 214

MEEG 211

IV

MEEG 202

MEEG 206

MEEG 207

MEEG 215

MATH 208

MCSC 202

MEEG 212

Third

V

COEG 304

MEEG 301

MEEG 306

MEEG 315

MGTS 301

MEEG 312

MEEG 305

VI

MEEG 3**

MEEG 3**

MEEG 308

MEEG 318

MGTS 3**

MEEG 313

MEEG 311

MEEG 313

Fourth

VII

MGTS 4**

MEEG 4**

MEEG 4**

MEEG 4**

MGTS 4**

MEEG 4**

MEEG 4**

VIII

MEEG 4**

MEEG 4**

First Year First Semester

S.No.

Course Code

Course Description

Credits

1

ENGG 111

Elements of Engineering I

3

2

MATH 101

Calculus and Linear Algebra

3

3

CHEM 101

General Chemistry

3

4

PHYS 101

General Physics I

3

5

ENGT 101

Communication Skills I

2

6

COMP 103

Structured Programming

2

7

EDRG 101

Engineering Drawing I

2

8

ENGG 101

Engineering Project Preparation

2

Total Credits

20

First Year Second Semester

S.No.

Course Code

Course Description

Credits

1

MATH 104

Advanced Calculus

3

2

PHYS 102

General Physics II

3

3

COMP 116

Object Oriented Programming

3

4

ENGG 112

Elements of Engineering II

3

5

ENGT 102

Communication Skills II

2

6

ENVE 101

Intro. To Environmental Engineering

2

7

EDRG 102

Engineering Drawing II

2

8

ENGG 102

Engineering Project

2

Total Credits

20

Second Year First Semester

S.No.

Course Code

Course Description

Credits

1

MATH 207

Diff. Equations & Complex Variables

4

2

MEEG 217

Basic Manufacturing Processes

3

3

MEEG 216

Engineering Mechanics

3

4

MEEG 213

Material Science & Metallurgy

3

5

EEEG 204

Basic Electronics

2

6

MEEG 219

Metrology

2

7

MEEG 214

Engineering Project

2

8

MEEG 211

Laboratory Works

2

Total Credits

21

Second Year Second Semester

S.No.

Course Code

Course Description

Credits

1

MEEG 207

Engineering Thermodynamics

3

2

MCSC 202

Numerical Methods

3

3

MATH 208

Statistics & Probability

3

4

MEEG 202

Strength of Materials

3

5

MEEG 206

Theory of Machines

3

6

MEEG 215

Engineering Project

2

7

MEEG 212

Laboratory Works

2

Total Credits

19

Third Year First Semester

S.No.

Course Code

Course Description

Credits

1

COEG 304

Instrumentation and Control

3

2

MEEG 301

Fluid Mechanics

3

3

MEEG 306

Heat Transfer

3

4

MEEG 315

Machine Element Design & Processes I

3

5

MGTS 301

Engineering Economics

3

6

MEEG 312

Engineering Project

2

7

MEEG 305

Laboratory Works

2

Total Credits

19

Third Year Second Semester

S.No.

Course Code

Course Description

Credits

1

MEEG 318

Machine Element Design & Processes II

3

2

MEEG 3**

Maintenance Engineering

3

3

MEEG 3**

Refrigeration & Air Conditioning

3

4

MEEG 308

Production Planning and Control

3

5

MGTS 3**

Engineering Management

3

6

MEEG 313

Engineering Project

2

7

MEEG 311

Laboratory Works

2

Total Credits

19

Fourth Year First Semester

S.No.

Course Code

Course Description

Credits

1

MGTS 4**

Engineering Entrepreneurship Development

3

2

MEEG 4**

Elective I

3

3

MEEG 4**

Elective II

3

4

MEEG 4**

Elective III

3

5

MEEG 4**

Elective IV

3

6

MEEG 4**

Engineering Project

2

7

MEEG 4**

Laboratory Works

2

Total Credits

19

Fourth Year Second Semester

S.No.

Course Code

Course Description

Credits

1

MEEG 4**

Industrial Training

6

2

  MEEG 4**

Engineering Project

6

Total Credits

12

B.E. In Mechanical Engineering (Subdivision)- Course Detail

In the curriculum, lectures are supported by case studies, group discussions, project assignments, field visits, class presentations and other teaching methods. Students' participation in class, group-discussions and individual presentations is highly emphasized to develop their leadership and communication skills.

Courses marked *** are elective courses offered at the final year of the undergraduate program. Students can choose specialized courses among the available elective courses within the subdivision as offered by the department.

0 comments

Leave a Reply

Your email address will not be published. Required fields are marked *