Introduction to Computational Modeling of Social Systems Prof. Lars-Erik Cederman Center for Comparative and International Studies (CIS) Seilergraben 49,

Slides:



Advertisements
Similar presentations
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++)
Advertisements

Collections CS3250. Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
15-Jun-15 Lists in Java Part of the Collections Framework.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
Using Linked Lists in java.util Package Linked Lists in java.util package: Introduction. LinkedList class of java.util package: Introduction. LinkedList.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
Java Review Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
The Java Collections Package C. DeJong Fall 2001.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
(c) University of Washington14-1 CSC 143 Java Collections.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Lecture 2: Classes and Objects, using Scanner and String.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
Geoff Holmes Palindrome solutions Overview Arrays Collections Enumerators Vector BitSet Stack Dictionary Hashtable Collection Classes (Chapter 19) import.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Introduction to Computational Modeling of Social Systems Prof. Lars-Erik Cederman Center for Comparative and International Studies (CIS) Seilergraben 49,
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
Data structures Abstract data types Java classes for Data structures and ADTs.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
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.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Practical Session 4 Java Collections. Outline Working with a Collection The Collection interface The Collection hierarchy Case Study: Undoable Stack The.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Introduction to Computational Modeling of Social Systems Prof. Lars-Erik Cederman Center for Comparative and International Studies (CIS) Seilergraben 49,
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Lecture 9: Lists MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture we will learn…. ArrayList – These are re-sizeable.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Introduction to Computational Modeling of Social Systems Nils Weidmann Center for Comparative and International Studies (CIS) Seilergraben 49, Room E.3,
1 Collections. 2 Concept A collection is a data structure – actually, an object – to hold other objects, which let you store and organize objects in useful.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
Java Collection Classes Com379PT
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
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.
Object Oriented Programming Lecture 2: BallWorld.
EKT472: Object Oriented Programming
COP 3503 FALL 2012 Shayan Javed Lecture 8
An Introduction to Java – Part I
Introduction to Collections
Introduction to Collections
TCSS 143, Autumn 2004 Lecture Notes
Lecture 6: Collections.
Introduction to Collections
An Introduction to Java – Part I, language basics
Introduction to Collections
Introduction to Collections
Collections Framework
Introduction to Collections
Web Design & Development Lecture 6
Part of the Collections Framework
Presentation transcript:

Introduction to Computational Modeling of Social Systems Prof. Lars-Erik Cederman Center for Comparative and International Studies (CIS) Seilergraben 49, Room G.2, Nils Weidmann, CIS Room E.3 Lecture, November 23, 2004 Java Primer III

2 Today’s agenda Packages Arrays –Statistics example Collections –SimpleList example

3 Creating a package Membership of a class in a package is defined by putting a package command at the top of the source code: package carPackage; public class Vehicle { (...) public void drive() { (...) } Package hierarchy: package topPackage.subPackage1.subPackage2;

4 Using packages By providing the fully-qualified package name: public class VehicleTest { carPackage.Vehicle v; public void driveTest() { v.drive(); } By making the packaged classes known to the compiler: import carPackage.Vehicle; // makes class „Vehicle“ visible import carPackage.*;// makes all classes in package // „carPackage“ visible

5 Java‘s built-in packages Java comes with a lot of ready-to-use classes for different purposes These classes are organized in packages For each package, a documentation is available (see java.sun.com/j2se/1.4.2/api)

6 Wrappers for the primitive data types, example: java.lang.Double „mother of all objects“: class Object Standard input and output streams: class System. Remember: public class Model { public static void main(String[] args) { System.out.println((int)sedan.getPersonMile() + " " + (int)roadster.getPersonMile() + " " + (int)suv.getPersonMile()); } Example: java.lang

7 Managing many agents Arrays and collections help the user handle many objects Both data types are objects Arrays are simpler and less powerful Collections are more complex but also more flexible

8 Arrays in Java An array holds a vector or matrix of data Arrays must be dynamically created: int a[] = new int[10]; Car parking[][] = new Car[n][m]; May also declare default values: int a[]={3,8,2,5,7,7,1,4,9,2} 3 1 a[0]= a[4]=7 a[9]=2 7

Multidimensional arrays int num = new int[3][3]; for(int i=0;i<3;i++) for(int j=0;j<3;j++) num[i][j]=i*3+j; Or: int num[][]={{0,1,2}, {3,4,5}, {6,7,8}}; num[2][1]=7

10 Statistics: Code public class Statistics { public static void main(String[] args) { int n = 10; int maxValue = 100; int x[] = new int[n]; int max = 0; int sum = 0; for (int i=0; i<n; i++) { x[i] = (int)(Math.random() * maxValue); System.out.print(x[i]+" "); } for (int i = 0; i<n; i++) { sum = sum + x[i]; if (x[i] > max) max = x[i]; } System.out.println(); System.out.println("mean = " + (double)sum/n + " max = " + max); } mean = 42.4 max = 94 Output:

11 Collections Java features collections Unlike arrays, collections are dynamic data structures holding objects* that can change during run-time Collections can be of type ArrayList, LinkedList, Set etc. (old type: Vector ) Read more: chap. in Eckel book or *) Simple types have to be wrapped: Integer etc.

12 Collections: Data types Collection SetList ArrayListLinkedList

13 Arrays and Linked Lists Arrays: fast access Linked Lists: flexibility

14 Lists in Java a1 a2 a3 a4 LinkedList list = new LinkedList(); Iterator it = list.iterator(); agent=(Agent)it.next(); list.add(a4);

15 Collections // Basic operations int size(); boolean isEmpty(); boolean contains(Object o); void add(Object o); void remove(Object o); Iterator iterator(); //... LinkedList also: Object get(int i); void set(int i, Object o); // etc. // Bulk operations boolean containsAll(Collection c); addAll(Collection c); removeAll(Collection c); retainAll(Collection c); clear(); // Iterator boolean hasNext(); Object next(); void remove(); //... ListIterator also: boolean hasPrevious(); Object previous; // Built-in algortihms: Collections.sort(List l); Collections.shuffle(List l); Collections.reverse(List l); Static methods, like Collections.shuffle() and Math.random() belong to a class rather than to an instance of a class; see Eckel! Object is a generic root class

16 Example: SimpleList Create agents with different height and gender Find average and max heights Sort list Divide it into girls and boys Concatenate the two sublists Scramble list

17 SimpleList: Sample output false true true false true true false false true true Average height: 4.84 Max height: 5.69 Sorted list: [4.03, 4.07, 4.53, 4.58, 4.67, 4.73, 4.97, 5.48, 5.67, 5.69] Girls: [4.03, 4.07, 4.58, 4.73, 4.97, 5.67] Boys: [4.53, 4.67, 5.48, 5.69] Boys and girls: [4.53, 4.67, 5.48, 5.69, 4.03, 4.07, 4.58, 4.73, 4.97, 5.67] Scrambled list: [4.67, 4.58, 4.03, 4.97, 4.53, 5.69, 5.48, 4.73, 4.07, 5.67]

18 SimpleList (Agent code) package simplelist; import java.text.*; public class Agent{ int id; boolean female; double height; public Agent(int i, boolean f, double h) { id = i; female = f; height = h; } public String toString() { return new DecimalFormat("###.00").format(height); } toString() method can be defined for printing all Java Objects,

19 SimpleList (Model code 1) package simplelist; import java.util.*; import java.text.*; public class Model { public static void main(String[] args) { int n = 10; boolean female; double height; // Creating list ArrayList list = new ArrayList();... import statements necessary when invoking packages that are not in the Java core

20 SimpleList (Model code 2) // Initializing list for (int i=0; i<n; i++) { if (Math.random()<0.5) { female = true; height = Math.random()*2.0; } else { female = false; height = Math.random()*2.5; } Agent a = new Agent(i,female,height); list.add(a); System.out.println(i+" "+ (new DecimalFormat("###.00").format(height))+ " "+female); }...

21 SimpleList (Model code 3) // Calculating average height double s = 0.0; Iterator it = list.iterator(); while (it.hasNext()) { Agent a = (Agent)it.next(); s = s + a.height; } System.out.println(„Average height: "+ (new DecimalFormat("###.00").format(s/(double)n))); // Calculating max height double max = 0.0; for (int i=0; i<list.size(); i++) { Agent a = (Agent)list.get(i); if (a.height > max) max = a.height; } System.out.println("Max height: "+ (new DecimalFormat("###.00").format(max))); Warning: get() and set() can be slow in a LinkedList Warning: Casting necessary

22 SimpleList (Model code 4) // Sorting list ArrayList temp = new ArrayList(); while (!list.isEmpty()) { Agent shortest = (Agent)list.get(0); for (int i=0; i<list.size(); i++) { Agent a = (Agent)list.get(i); if (a.height < shortest.height) shortest = a; } list.remove(shortest); temp.add(shortest); } list = temp; System.out.println("Sorted list: "+list);... Collections are printed as lists with the elements defined by toString() Note: There is a pre-defined, efficient routine: Collections.sort()

23 SimpleList (Model code 5) // Creating list of girls ArrayList girls = new ArrayList(list); it = girls.iterator(); while (it.hasNext()) { Agent a = (Agent)it.next(); if (!a.female) it.remove(); } System.out.println("Girls: "+girls); // Creating list of boys ArrayList boys = new ArrayList(); it = list.iterator(); while (it.hasNext()) { Agent a = (Agent)it.next(); if (!a.female) boys.add(a); } System.out.println("Boys: "+boys); Warning: Be careful when removing objects while iterating: remove() can only be called once per next()

24 SimpleList (Model code 6) // Concatenating the two lists ArrayList boysAndGirls = new ArrayList(boys); boysAndGirls.addAll(girls); System.out.println("Boys and girls: "+boysAndGirls); // Shuffling the original list Collections.shuffle(list); System.out.println("Scrambled list: "+list);