Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Introduction to Computational Modeling of Social Systems Java Primer III Prof. Lars-Erik Cederman Center for Comparative and International Studies (CIS) Seilergraben 49, Room G.2, [email protected] Nils Weidmann, CIS Room E.3 [email protected] http://www.icr.ethz.ch/teaching/compmodels Lecture, November 23, 2004 Today’s agenda • Packages • Arrays – Statistics example • Collections – SimpleList example 2 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; 3 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; import carPackage.*; // makes class „Vehicle“ visible // makes all classes in package // „carPackage“ visible 4 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) 5 Example: java.lang • 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()); } } 6 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 7 Arrays in Java 8 • 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 8 a[0]=3 2 5 7 7 1 a[4]=7 4 9 2 a[9]=2 Multidimensional arrays 9 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 0 0 0 1 1 2 2 1 3 4 5 2 6 7 8 Statistics: Code 10 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); } } Output: 10 26 38 16 27 30 94 40 54 89 mean = 42.4 max = 94 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. 11 Collections: Data types 12 Collection Set List ArrayList LinkedList Arrays and Linked Lists 13 Arrays: fast access 0 3 1 8 2 2 3 5 4 7 5 7 6 1 7 4 8 9 9 2 Linked Lists: flexibility 3 8 5 2 7 Lists in Java 14 LinkedList list = new LinkedList(); Iterator it = list.iterator(); agent=(Agent)it.next(); list.add(a4); a1 a2 a3 a4 Collections 15 // Basic operations // Iterator int size(); boolean hasNext(); boolean isEmpty(); Object next(); boolean contains(Object o); void remove(); void add(Object o); // ... ListIterator also: void remove(Object o); boolean hasPrevious(); Object is a Iterator iterator(); Object previous; generic root // ... LinkedList also: class Object get(int i); // Built-in algortihms: void set(int i, Object o); Collections.sort(List l); // etc. Collections.shuffle(List l); // Bulk operations Collections.reverse(List l); boolean containsAll(Collection c); addAll(Collection c); removeAll(Collection c); retainAll(Collection c); Static methods, like Collections.shuffle() clear(); and Math.random()belong to a class rather than to an instance of a class; see Eckel! 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 16 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] 17 SimpleList (Agent code) 18 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; } toString() method can be defined for printing all Java Objects, public String toString() { return new DecimalFormat("###.00").format(height); } } SimpleList (Model code 1) package simplelist; import java.util.*; import java.text.*; import statements necessary when invoking packages that are not in the Java core public class Model { public static void main(String[] args) { int n = 10; boolean female; double height; // Creating list ArrayList list = new ArrayList(); ... 19 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); } ... 20 SimpleList (Model code 3) // Calculating average height double s = 0.0; Iterator it = list.iterator(); while (it.hasNext()) { Agent a = (Agent)it.next(); Warning: Casting s = s + a.height; necessary } 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++) { Warning: Agent a = (Agent)list.get(i); get() and set() can be slow in a LinkedList if (a.height > max) max = a.height; } System.out.println("Max height: "+ (new DecimalFormat("###.00").format(max))); 21 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; Collections are } printed as lists list.remove(shortest); with the elements temp.add(shortest); defined by } toString() list = temp; System.out.println("Sorted list: "+list); ... Note: There is a pre-defined, efficient routine: Collections.sort() 22 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() 23 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); 24