1 נתבונן בפונקציה הבאה public static int min(int[] a,int n) { int min = a[0]; for (int i = 1; (i < n ) && (i < a.length) ; i++) if (min > a[i]) min = a[i];

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Inheritance // A simple class hierarchy. // A class for two-dimensional objects. class TwoDShape { double width; double height; void showDim() { System.out.println("Width.
CS18000: Problem Solving and Object-Oriented Programming.
תוכנה 1 סמסטר א ' תשע " ב תרגול מס ' 7 * מנשקים, דיאגרמות וביטים * לא בהכרח בסדר הזה.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { } public ABC () {} public.
Java Review Interface, Casting, Generics, Iterator.
Exercise 1 Suppose C is a class that implements interfaces I and J. Which of the following Requires a type cast? C c = ……? I i = …..? J j = …..? c =
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב'
Arrays An array is a collection of variables, all of the same type. An array is created with the new operator. The size of an array must be specified at.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
תכנות תרגול 6 שבוע : תרגיל שורש של מספר מחושב לפי הסדרה הבאה : root 0 = 1 root n = root n-1 + a / root n-1 2 כאשר האיבר ה n של הסדרה הוא קירוב.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
CSC 160 Practice Final Review. Question 1 class A { public void blah() { System.out.println("a"); } class B extends A { public void blah() { System.out.println("b");
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
Introduction to Searching and Sorting
Sscanf example #include int main () { char sentence []="Rudolph is 12 years old"; char str [20]; int i; sscanf (sentence,"%s %*s %d",str,&i); printf ("%s.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
Arrays And ArrayLists - S. Kelly-Bootle
Advanced Java Session 3 New York University School of Continuing and Professional Studies.
1 Lecture 09 Iterators and Enumerations Reading for these lectures: Weiss, Section Iterator Interface. Much better is: ProgramLive, Section 12.3.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
04/29/ Introduction to Vectors?... A vector is a dynamic array. - It can be expanded and shrunk as required - A Component of a vector can be accessed.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
תרגול 13 חזרה 1. Exam example 8 public class Stam { private char x; public Stam() { this.x = '*'; } public Stam (char c) { this.x = c; } public Stam getStam()
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
Java 2 Collections Bartosz Walter Software Engineering II.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Overriding toString()
Arrays and Objects CIS 362. The familiar Employee class.
AITI Lecture 18 Introduction to Data Structure, Stack, and Queue Adapted from MIT Course 1.00 Spring 2003 Lecture 23 and Tutorial Note 8 (Teachers: Please.
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?
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Interfaces and Inner Classes
ABSTRACT DATA TYPES, ABSTRACT CLASSES AND INTERFACES And abstract art….
1 Inheritance and Subclasses. 2 Inheritance Often we create very similar classes –Different types of triangles: equilateral, isosceles, etc. –Different.
Chapter One Lesson Three DATA TYPES ©
A: A: double “4” A: “34” 4.
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
Java Programming Persistent Data Types. Persistent Data Structure A persistent data structure is a data structure having an internal state that never.
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
1 Iterator Pattern (A Behavioral Pattern) Prepared by: Neha Tomar.
Polymorphism & Intefaces Tirgul 8. Ex4 - Common mistakes (input from the testers) Javadoc inside the method instead above it No use of magic number in.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
יסודות מדעי המחשב – תרגול 6
Programming Arrays.
using System; namespace Demo01 { class Program
Ch 14: Search and Sorting Yonglei Tao.
Function Call Trace public class Newton {
More About Objects and Methods CS140: Introduction to Computing 1 Savitch Chapter 6 10/16/13.
Iteration Abstraction
Review Operation Bingo
בניית מחלקות.
null, true, and false are also reserved.
CSE 1030: Implementing Mixing static and non-static features
CSE 1030: Implementing Non-Static Features
בניית מחלקות.
Code Animation Examples
class PrintOnetoTen { public static void main(String args[]) {
COMPUTER 2430 Object Oriented Programming and Data Structures I
ITI Introduction to Computing II Lab-12
Presentation transcript:

1 נתבונן בפונקציה הבאה public static int min(int[] a,int n) { int min = a[0]; for (int i = 1; (i < n ) && (i < a.length) ; i++) if (min > a[i]) min = a[i]; return min; } הפונקציה מחזירה לכל מערך של מספרים שלמים את המספר הנמוך ביותר בו. ניתן כמובן לכתוב פונקציה כזו עבור טיפוסי עצמים רבים ושונים זה מזה : מספרים, מחרוזות, תלמידים וכו '. היינו מעדיפים לכתוב את הקוד פעם אחת.

2 הכלי המאפשר לנו זאת הוא הממשק Comparable (interface). המוגדר על ידי // public int compareTo(Object obj) returns: // a positive integer if this > obj // zero if this = obj // a negative integer if this < obj Public interface Comparable { public int compareTo(Object obj); }

3 public class Util { public static Comparable min(Comparable[] a,int n) { Comparable min = a[0]; for (int i = 1; (i < a.length) && (a[i] != null) && (i < n); i++) if (min.compareTo(a[i]) > 0) min = a[i]; return min; } כעת ניתן לכתוב את הפונקציה מחדש בתוך המחלקה Util:

4 נותר רק ליישם את הממשק ע " י המחלקות השונות לדוגמה public class Integer implements Comparable { : public int compareTo(Object other) { if (! (other instanceof Integer)) { System.out.println(“Cannot compare Integer to “+other); return 10000; } if (intValue() >((Integer) other).intValue()) return 1; if (intValue() <((Integer) other).intValue()) return -1; return 0; } : }

5 או Public class String implements Comparable { : public int compareTo(String other) public int compareTo(Object other) { if (! (other instanceof Integer)) { System.out.println(“Cannot compare Integer to “+other); return 10000; } for (int i = 0; (i < size() )& (i <other.size()); i++) { if (charAt(i) > other.charAt(i)) return 1; if (charAt(i) < other.charAt(i)) return -1; } if (size() >other.size()) return 1; if (size() < other.size()) return –1; return 0; }

6 וגם public class TwoDvector implements Comparable{ private double x,y; public TwoDvector(double x,double y) { this.x = x; this.y = y; } public String toString() { return "( "+x+", "+y+" )"; } public double x() { return x;} public double y() { return y;}

7 public int compareTo(Object compare_me) { if (! (compare_me instanceof TwoDvector)) { System.out.println("cannot compare a "+ "twoDvector to "+compare_me); return ; } TwoDvector other = (TwoDvector) compare_me; double my_length = Math.sqrt(x*x+y*y); double other_length = Math.sqrt(other.x()*other.x()+ other.y()*other.y()); if (my_length > other_length) return 1; if (my_length < other_length) return -1; return 0; }

8 public class TwoDvector_driver { public static void main(String[] args) { TwoDvector[] vectors = new TwoDvector[100]; vectors[0] = new TwoDvector(1,2); vectors[1] = new TwoDvector(0.5,2); vectors[2] = new TwoDvector(0.5,1); System.out.println(Tools.min(vectors,3)); } הפלט ( 0.5, 1.0 )

9 ניתבונן כעת בממשק Set public interface Set { public boolean add(Object addMe); public Iterator iterator(); public boolean contains(Object obj); public boolean equals(Set other); public int size(); }

10 ובממשק Iterator public interface Iterator { public boolean hasNext(); public Object next(); }

11 public class SimpleSet implements Set{ public static final int DEFAULT_CAPACITY = 100; private int capacity; private int n_members; private Object[] members; public SimpleSet() { this(DEFAULT_CAPACITY); } public SimpleSet(int capacity) { this.capacity = capacity; members = new Object[capacity]; } נציג ישום אחד שלהם במחלקה SimpleSet

12 public boolean add(Object add_me) { if (contains(add_me)) return false; if (n_members == capacity) { capacity = capacity + DEFAULT_CAPACITY ; Object[] new_members = new Object[capacity]; for (int i = 0; i < n_members; i++) new_members[i] = members[i]; members = new_members; } members[n_members] = add_me; n_members++; return true; }

13 public boolean contains(Object other) { for (int i = 0; i < n_members; i++) if (members[i].equals(other)) return true; return false; } public int size() { return n_members; } public Iterator iterator() { return (Iterator) new SimpleSetIterator(); }

14 public class SimpleSetIterator implements Iterator { private int current; public SimpleSetIterator() { current = 0; } public boolean hasNext() { return current < n_members; } public Object next() { current = current+1; return members[current - 1]; }

15 public boolean equals (Object test_me) { if (! (test_me instanceof Set)) return false; Set other = (Set) test_me; if (size() != other.size()) return false; Iterator it = iterator(); while (it.hasNext()) if (! other.contains(it.next())) return false; return true; } } // class SimpleSet

16 public class Set_driver { public static void main(String[] args) { SimpleSet my_set = new SimpleSet(2); my_set.add(new Integer(1)); my_set.add(new Double(50)); my_set.add("Happy new year"); Iterator it = my_set.iterator(); while (it.hasNext()) System.out.println(it.next());

17 SimpleSet your_set = new SimpleSet(); your_set.add(new Double(50)); your_set.add(new Integer(1)); your_set.add("Happy new year"); it = your_set.iterator(); while (it.hasNext()) System.out.println(it.next()); System.out.println(my_set.equals(your_set)); System.out.println(my_set == your_set); }

Happy new year Happy new year true false פלט