Object-Oriented Programming in the Java language

Similar documents
The class Object. Lecture CS1122 Summer 2008

equals() in the class Object

ArrayList. Introduction. java.util.arraylist

Super-Classes and sub-classes

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Algorithms. Produced by. Eamonn de Leastar

CONTAİNERS COLLECTİONS

Creating an Immutable Class. Based on slides by Prof. Burton Ma

Generics method and class definitions which involve type parameters.

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

What is the Java Collections Framework?

Methods Common to all Classes

COMP 250 Fall inheritance Nov. 17, 2017

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

For this section, we will implement a class with only non-static features, that represents a rectangle

Java Fundamentals (II)

COMP 250. Lecture 30. inheritance. overriding vs overloading. Nov. 17, 2017

Programming Languages and Techniques (CIS120)

java.lang.object: Equality

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

CSC 1214: Object-Oriented Programming

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Programming Languages and Techniques (CIS120)

Elementary Symbol Tables

Interfaces, collections and comparisons

Introduction to Java. CSC212 Lecture 6 D. Thiebaut, Fall 2014

The Java Collections Framework and Lists in Java Parts 1 & 2

Chapter 11: Collections and Maps

9/16/2010 CS Ananda Gunawardena

CS Ananda Gunawardena

Generics and collections

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Uguaglianza e Identità. (no, non avete sbagliato corso )

Generic classes & the Java Collections Framework. *Really* Reusable Code

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

Programming Languages and Techniques (CIS120)

MET08-J. Preserve the equality contract when overriding the equals() method

List... NOTE We use List as illustrative example of collections Study the others from textbook!

Array Based Lists. Collections

Generics and the. ArrayList Class CHAPTER

1. Every program must have at least one class declaration. (*) 2. Every class declared in a program must have a distinct identifier.

Rules and syntax for inheritance. The boring stuff

EECS 2011 M: Fundamentals of Data Structures

Generics Collection Framework

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

CS1083 Week 2: Arrays, ArrayList

Expected properties of equality

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Java Collections Framework: Interfaces

CSE 8B Intro to CS: Java

CSE 331 Software Design & Implementation

Collections, Maps and Generics

The Liskov Substitution Principle

Class 32: The Java Collections Framework

The Java Collections Framework. Chapters 7.5

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Introduction to Functional Programming in Java 8

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

boolean add(object o) Method Description (from docs API ) Method Description (from docs API )

CMSC 132: Object-Oriented Programming II

Announcements. Equality. Lecture 10 Equality and Hashcode. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

Equality in.net. Gregory Adam 07/12/2008. This article describes how equality works in.net

Chapter 4 Defining Classes I

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

Introduction to Object-Oriented Programming

6.005 Elements of Software Construction Fall 2008

1. ArrayList and Iterator in Java

COSC 123 Computer Creativity. Java Lists and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

Week 4, Wednesday (Spring 2015). Dr. Yoder. Sec 051. Page 1 of 5

CSE 331 Software Design & Implementation

CS 170, Section /3/2009 CS170, Section 000, Fall

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

ELEMENTARY SEARCH ALGORITHMS

Student Number: Legibly write your name and student number on this page. Legibly write your name on the back page of this exam.

AP CS Unit 7: Interfaces. Programs

Java Language Features

Class, Variable, Constructor, Object, Method Questions

CMSC 202. Containers

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Dynamic Data Structures and Generics

Exercise 8 Parametric polymorphism November 18, 2016

Programming Languages and Techniques (CIS120)

Lecture 6: ArrayList Implementation

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Problem 1: Building and testing your own linked indexed list

CO Java SE 8: Fundamentals

Equality. Michael Ernst. CSE 331 University of Washington

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

Generalized Code. Fall 2011 (Honors) 2

Transcription:

Object-Oriented Programming in the Java language Part 6. Collections(1/2): Lists. Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua

Just before we start Generics Generics are a language feature introduced to Java in version 1.5. Before generics were introduced in Java, the Object base class was used as an alternative to generics. With generics, you write code for one type (say T) that is applicable for all types, instead of writing separate classes for each type.

Example class BoxPrinter<T> { private T val; public BoxPrinter(T arg) { val = arg; public String tostring() { return "[" + val + "]"; BoxPrinter<Integer> value1 = new BoxPrinter<Integer>(new Integer(10)); System.out.println(value1); BoxPrinter<String> value2 = new BoxPrinter<String>("Hello world"); System.out.println(value2);

Notes for example 1. See the declaration of BoxPrinter: class BoxPrinter<T> You gave the BoxPrinter class a type placeholder <T> the type name T within angle brackets < and > following the class name. You can use this type name inside the class to indicate that it is a placeholder for the actual type to be provided later.

Notes for example 2. Inside the class you first use T in field declaration: private T val; You are declaring val of the generic type the actual type will be specified later when you use BoxPrinter. In main(), you declare a variable of type BoxPrinter for an Integer like this: BoxPrinter<Integer> value1 Here, you are specifying that T is of type Integer identifier T (a placeholder) is replaced with the type Integer. So, the val inside BoxPrinter becomes Integer because T gets replaced with Integer.

Notes for example 3. Now, here is another place where you use T: public BoxPrinter(T arg) { val = arg; Similar to the declaration of val with type T, you are saying that the argument for BoxPrinter constructor is of type T. Later in the main() method, when the constructor is called in new, you specify that T is of type Integer: new BoxPrinter<Integer>(new Integer(10));

Example class Pair<T1, T2> { T1 object1; T2 object2; Pair(T1 one, T2 two) { object1 = one; object2 = two; public T1 getfirst() { return object1; public T2 getsecond() { return object2; Pair<Integer, String> worldcup = new Pair<Integer, String>(2018, "Russia"); System.out.println("World cup " + worldcup.getfirst() + " in " + worldcup.getsecond());

Diamond Syntax To simplify your life, Java 1.7 introduced the diamond syntax, in which the type parameters may be omitted: you can just leave it to the compiler to infer the types from the type declaration. So, the declaration can be simplified as Pair<Integer, String> worldcup = new Pair<>(2018, "Russia"); Note that it is a common mistake to forget the diamond operator < > in the initialization expression, as in

ArrayList This lecture covers only one class from the Java Collection API: ArrayList. The rest of the classes from the Java Collection API are covered in next one. One of the reasons to include this class in the first part could be how frequently this class is used by all Java programmers. ArrayList is one of the most widely used classes from the Collections framework. It offers the best combination of features offered by an array and the List data structure. The most commonly used operations with a list are: add items to a list, modify items in a list, delete items from a list, and iterate over the items

Using of ArrayList One frequently asked question by Java developers is, Why should I bother with an ArrayList when I can already store objects of the same type in an array? The answer lies in the ease of use of an ArrayList. You can compare an ArrayList with a resizable array. As you know, once it s created, you can t increase or decrease the size of an array. On the other hand, an ArrayList automatically increases and decreases in size as elements are added to or removed from it. Also, unlike arrays, you don t need to specify an initial size to create an ArrayList.

Important properties It implements the interface List. of ArrayList It allows null values to be added to it. It implements all list operations (add, modify, and delete values). It allows duplicate values to be added to it. It maintains its insertion order. You can use either Iterator or ListIterator to iterate over the items of an ArrayList. It supports generics, making it type safe. (You have to declare the type of the elements that should be added to an ArrayList with its declaration.)

Creating an ArrayList Let s see: ArrayList<String> myarrlist = new ArrayList<String>(); Starting with Java version 7, you can omit the object type on the right side of the equal sign and create an ArrayList as follows: ArrayList<String> myarrlist = new ArrayList<>();

Adding elements to an ArrayList ArrayList<String> list = new ArrayList<>(); list.add("one"); list.add("two"); list.add("four"); list.add(2, "three");

Adding elements to an ArrayList

Using enhanced for loop: Accessing elements of an ArrayList ArrayList<String> myarrlist = new ArrayList<>(); myarrlist.add("one"); myarrlist.add("two"); myarrlist.add("four"); myarrlist.add(2, "Three"); for (String element : myarrlist) { System.out.println(element); Using ListIterator: ListIterator<String> iterator = myarrlist.listiterator(); while (iterator.hasnext()) { System.out.println(iterator.next());

Modifying the elements of an ArrayList ArrayList<String> myarrlist = new ArrayList<>(); myarrlist.add("one"); myarrlist.add("two"); myarrlist.add("three"); myarrlist.set(1, "One and Half"); for (String element:myarrlist) { System.out.println(element);

Deleting the elements of an ArrayList ArrayList<String> myarrlist = new ArrayList<>(); String s1 = "One"; String s2 = "Two"; String s3 = "Three"; String s4 = "Four"; myarrlist.add(s1); myarrlist.add(s2); myarrlist.add(s3); myarrlist.add(s4); myarrlist.remove(1); for (String element:myarrlist) { System.out.println(element); myarrlist.remove(s3); myarrlist.remove("four"); System.out.println(); for (String element : myarrlist) { System.out.println(element);

Example

Other methods of ArrayList ADDING MULTIPLE ELEMENTS TO AN ARRAYLIST You can add multiple elements to an ArrayList from another ArrayList or any other class that s a subclass of Collection by using the following overloaded versions of method addall: addall(collection<? extends E> c) addall(int index, Collection<? extends E> c)

Other methods of ArrayList ADDING MULTIPLE ELEMENTS TO AN ARRAYLIST ArrayList<String> myarrlist = new ArrayList<>(); myarrlist.add("one"); myarrlist.add("two"); ArrayList<String> yourarrlist = new ArrayList<>(); yourarrlist.add("three"); yourarrlist.add("four"); myarrlist.addall(1, yourarrlist); for (String val : myarrlist) { System.out.println(val);

Other methods of ArrayList CLEARING ARRAYLIST ELEMENTS You can remove all the ArrayList elements by calling clear on it. ArrayList<String> myarrlist = new ArrayList<>(); myarrlist.add("one"); myarrlist.add("two"); myarrlist.clear(); for (String val:myarrlist) { System.out.println(val);

Other methods of ArrayList ACCESSING INDIVIDUAL ARRAYLIST ELEMENTS get(int index) returns the element at the specified position in this list. size() returns the number of elements in this list. contains(object o) returns true if this list contains the specified element. indexof(object o) returns the index of the first occurrence of the specified element in this list, or -1 if this list doesn t contain the element. lastindexof(object o) returns the index of the last occurrence of the specified element in this list, or -1 if this list doesn t contain the element.

Other methods of ArrayList ACCESSING INDIVIDUAL ARRAYLIST ELEMENTS Three methods: contains, indexof, and lastindexof require you to have an unambiguous and strong understanding of how to determine the equality of objects. ArrayList stores objects, and these three methods will compare the values that you pass to these methods with all the elements of the ArrayList

Equality of Objects By default, objects are considered equal if they are referred to by the same variable (the String class is an exception with its pool of String objects). If you want to compare objects by their state (values of the instance variable), override the equals method in that class.

Equality of Objects The equals method implements an equivalence relation on non-null object references: It is reflexive: for any non-null reference value x, x.equals(x) should return true. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals() comparisons on the objects is modified. For any non-null reference value x, x.equals(null) should return false.

Other methods of ArrayList CREATING AN ARRAY FROM AN ARRAYLIST You can use the method toarray to return an array containing all the elements in an ArrayList in sequence from the first to the last element. Method toarray creates a new array, copies the elements of the ArrayList to it, and then returns it. Now comes the tricky part. No references to the returned array, which is itself an object, are maintained by the ArrayList. But the references to the individual ArrayList elements are copied to the returned array and are still referred to by the ArrayList

Example

Questions?

Object-Oriented Programming in the Java language Part 6. Collections(1/2): Lists. Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua