Download presentation
Presentation is loading. Please wait.
Published byPercival Norris Modified over 9 years ago
1
Introduction to Computational Modeling of Social Systems Prof. Lars-Erik Cederman Center for Comparative and International Studies (CIS) Seilergraben 49, Room G.2, lcederman@ethz.chlcederman@ethz.ch Nils Weidmann, CIS Room E.3 weidmann@icr.gess.ethz.chweidmann@icr.gess.ethz.ch http://www.icr.ethz.ch/teaching/compmodels Lecture, November 23, 2004 Java Primer III
2
2 Today’s agenda Packages Arrays –Statistics example Collections –SimpleList example
3
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
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
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
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
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
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]=3 8257492 a[4]=7 a[9]=2 7
9
9 012 0 1 2 012 345 678 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
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); } 10 26 38 16 27 30 94 40 54 89 mean = 42.4 max = 94 Output:
11
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 http://java.sun.com/docs/books/tutorial/collections/ *) Simple types have to be wrapped: Integer etc.
12
12 Collections: Data types Collection SetList ArrayListLinkedList
13
13 Arrays and Linked Lists 3 1 8 2574927 Arrays: fast access 3 8 2 5 Linked Lists: flexibility 7 0123456789
14
14 Lists in Java a1 a2 a3 a4 LinkedList list = new LinkedList(); Iterator it = list.iterator(); agent=(Agent)it.next(); list.add(a4);
15
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
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
17 SimpleList: Sample output 0 4.53 false 1 4.58 true 2 5.67 true 3 4.67 false 4 4.97 true 5 4.07 true 6 5.69 false 7 5.48 false 8 4.73 true 9 4.03 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
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
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
20 SimpleList (Model code 2) // Initializing list for (int i=0; i<n; i++) { if (Math.random()<0.5) { female = true; height = 4.0 + Math.random()*2.0; } else { female = false; height = 4.5 + 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
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
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
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
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);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.