Java Arrays Java has a static array capable
Java Arrays Java has a static array capable of easy multidimensions. Java has a dynamic array, which is also capable of multi-dimensions, but it is more complex. The Array. List class is used for the dynamic array. Static arrays have no methods, but have the initializer list. Array. List is a class with many methods.
// Java 1201. java // This program introduces the <Array. List> class and the <add> method. // Note that each name is added to the end of the list. // Ignore the warning messages about "unsafe operations" which // will be explained later and avoided. import namesjava. util. Array. List; contains [Isolde, John, Greg, Maria, Heidi] public class Java 1201 { public static void main(String[] args) { Array. List names = new Array. List(); names. add("Isolde"); names. add("John"); names. add("Greg"); names. add("Maria"); names. add("Heidi"); System. out. println("names contains " + names); } }
Array. List Method add names. add("Tom"); The add method allocates space for the newly enlarged array and then stores the new array element at the end of the Array. List object.
Displaying Array. List Elements Array. List elements can be accessed with various methods. It is possible to display all the elements inside square brackets, separated by commas by using the println method. System. out. println(names); [Isolde, John, Greg, Maria, Heidi]
// Java 1202. java names contains [Isolde, John, Greg] // This program uses the <size> method to determine the number of elements There are 3 object. elements names object. // in an <Array. List> The <length> in field isthe only for static arrays. // Note that the value returned[Isolde, by the <size> method changes. Greg, when more. Maria, names contains John, // are added to the <Array. List> object. Heidi] There are 5 elements in the names object. import java. util. Array. List; public class Java 1202 { public static void main(String[] args) { Array. List names = new Array. List(); names. add("Isolde"); names. add("John"); names. add("Greg"); System. out. println("names contains " + names); ; System. out. println("There are " + names. size() + " elements in the names object. "); names. add("Maria"); names. add("Heidi"); System. out. println("names contains " + names); System. out. println("There are " + names. size() + " elements in the names object. "); } }
Array. List Method size int count = names. size(); The size method returns the number of elements of the Array. List object names. Remember Java static arrays use a length field while Array. List uses a size method.
// Java 1203. java // This program shows how to access specified elements in an <Array. List> object // with the <get(k)> method. This compares to using [k] in static arrays. import java. util. Array. List; public class Java 1203 { public static void main(String[] args) { Array. List names = new Array. List(); names. add("Isolde"); names. add("John"); names. add("Greg"); names. add("Maria"); names. add("Heidi"); Isolde John Greg Maria Heidi Maria for (int k = 0; k < names. size(); k++) System. out. println(names. get(k) ); Greg System. out. println(); John for (int k = names. size()-1; k >= 0; k--) Isolde System. out. println(names. get(k)); } }
Array. List Access Array. List objects cannot be accessed with an index [ ] operator, like a Java static array. All access is performed with Array. List methods. ACCESS DENIED!
Array. List Method get System. out. println(names. get(3)); The get method accesses a specified array element. The parameter of the get method is the index of the Array. List object and starts at 0. Any attempt to access an element at a non-existing index results in an Index. Out. Of. Bounds. Exception error message.
// Java 1204. java names contains [Isolde, John, Greg, Maria, Heidi] // This program demonstrates the <set> method of the <Array. List> class, which // replaces existing elements with a new object. Heidi // Note that the <set> method is a return method that returns the last // element value before it is[Isolde, replaced. names contains Jessica, Anthony, Haley, Alec] import java. util. Array. List; public class Java 1204 { public static void main(String[] args) { Array. List names = new Array. List(); names. add("Isolde"); names. add("John"); names. add("Greg"); names. add("Maria"); names. add("Heidi"); System. out. println("names contains " + names); System. out. println(); names. set(1, "Jessica"); names. set(2, "Anthony"); names. set(3, "Haley"); System. out. println(names. set(4, "Alec")); } } System. out. println("names contains " + names);
Array. List Method set names. set(4, "Tom"); The set method uses the first parameter as the index location to find an array element and then replaces it with the value of the second set parameter. You will get an error if you try to access an index location, which has not been allocated yet. The set method also returns the last value before replacing it.
// Java 1205. java names Size: 5 // This program demonstrates the <remove> method of the <Array. List> names contains // class to delete a specified[Isolde, list element. John, Greg, Maria, // Dynamic arrays change size when they get bigger or smaller. names contains [Isolde, John, Maria, Heidi] import java. util. Array. List; Heidi] public class Java 1205 names contains [Isolde, John, Maria] { static 3 void main(String[] args) names public Size: { Array. List names = new Array. List(); names. add("Isolde"); names. add("John"); names. add("Greg"); names. add("Maria"); names. add("Heidi"); System. out. println("names Size: " +names. size()); System. out. println("names contains " + names); System. out. println(); names. remove(2); System. out. println("names contains " + names); System. out. println(); names. remove(3); } } System. out. println("names contains " + names); System. out. println("names Size: " +names. size());
Array. List Method remove names. remove(3); The remove method removes the array element at the index location of its parameter and decreases the object size by one array element.
names contains [Isolde, John, Greg, Maria, Heidi] // Java 1206. java // This program demonstrates how to use the overloaded <add> method of the // <Array. List> class [Isolde, to insert new elements at a specified location. names contains John, Jessica, Greg, Maria, Heidi] import names java. util. Array. List; contains [Isolde, John, Jessica, Anthony, Greg, Maria, Heidi] public class Java 1206 { public static void main(String[] args) { Array. List names = new Array. List(); names. add("Isolde"); names. add("John"); names. add("Greg"); names. add("Maria"); names. add("Heidi"); System. out. println("names contains " + names); System. out. println(); names. add(2, "Jessica"); System. out. println("names contains " + names); System. out. println(); names. add(3, "Anthony"); } } System. out. println("names contains " + names);
Array. List Method add (2 nd Overloaded method) names. add(3, "Kathy"); The overloaded add(3, "Kathy") method adds or rather inserts a new array element at the indicated index.
AP Exam Alert The Array. List class is tested on the AP exam with the following six methods: int size() boolean add(E obj) void add(int index, E obj) E get(int index) E set(int index, E obj) E remove(int index) In the method headings above E is the data type of the Element that is added or returned.
// Java 1207. java // This program demonstrates how <int> values stored into an <Array. List> object are first // converted to <Integer> objects. The <Integer> class is called a "wrapper" class. import java. util. Array. List; public class Java 1207 { public static void main(String[] args) { Array. List numbers = new Array. List(); for (int k = 1; k <= 500; k++) { int rnd. Int = (int) (Math. random() * 900 + 100); numbers. add(new Integer(rnd. Int)); System. out. print(rnd. Int + " "); if (k % 15 == 0) System. out. println(); } int sum = 0; for (int k = 0; k < numbers. size(); k++) { Integer temp = (Integer) numbers. get(k); sum += temp. int. Value(); } } } System. out. println("nn. Sum: " + sum);
637 799 561 150 756 984 702 756 639 620 355 770 869 444 596 838 211 633 972 788 354 736 413 787 349 551 151 912 317 512 377 715 263 657 402 283 977 983 350 750 189 753 752 984 236 151 826 983 896 877 327 872 802 482 135 664 373 175 449 397 862 482 753 869 402 206 290 840 417 771 979 813 724 775 396 406 365 275 515 699 479 978 283 500 532 116 153 118 451 576 241 520 736 703 944 382 766 979 858 956 691 558 Sum: 274662 787 543 634 812 334 794 564 512 495 672 677 449 981 484 386 565 304 427 138 559 555 406 441 902 228 540 947 693 524 476 103 260 426 510 501 198 621 300 412 268 539 452 726 238 311 606 741 942 440 783 168 294 928 449 286 412 113 617 727 284 207 813 491 681 758 160 327 259 596 906 319 252 181 543 920 454 427 569 139 800 740 765 622 827 195 248 337 225 943 274 878 286 668 463 653 835 203 936 426 515 480 232 940 645 431 832 407 404 483 968 724 910 534 722 500 452 271 794 187 587 850 246 727 700 986 270 980 521 202 264 130 732 270 240 336 432 573 621 988 357 733 747 558 172 387 383 363 438 857 129 900 740 579 895 547 536 150 980 136 941 497 853 107 583 223 269 416 420 406 815 308 834 382 443 367 756 228 759 181 907 495 700 908 220 858 162 752 568 350 729 966 776 709 536 126 594 966 771 244 904 212 778 847 584 988 951 102 767 351 364 526 383 287 671 873 178 549 615 541 117 277 741 609 996 540 141 931 642 196 788 352 960 284 942 659 744 221 730 391 268 610 226 613 723 426 797 521 906 989 721 973 819 493 395 404 801 714 151 489 251 168 383 209 501 228 227 679 656 247 622 741 577 551 414 998 945 526 493 946 346 131 624 461 843 677 691 419 203 486 113 280 761 500 186 619 477 564 700 917 969 315 402 770 741 230 804 166 758 985 200 197 467 227 804 443 928 851 290 973 319 661 389 633 107 425 835 525 689 443 498 371 372 344 194 938 904 940 626 946 816 440 468 325 426 216 792 763 232 925 460 145 874 738 347 287 451 251 862 207 433 100 981 376 603 716 875 619 673 990 346 851 436 619 792 502 486 564 839 336 234 416 194 795 422 177 389 662 529 350 684 114 756 359 248 622 763 889
Array. List and Primitive Data Types The Array. List class can only store Object values. Primitive data type values can be stored indirectly using wrapper classes. The Integer class wraps int values. The Double class wraps double values. The Boolean class wraps boolean values.
// Java 1208. java // This program has no output, which does not matter, because it does not compile. // You will see two "incompatible types" syntax errors. This may seem strange // because the <Array. List> object stores <Person> objects. import java. util. Array. List; public class Java 1208 { public static void main(String[] args) { Array. List people = new Array. List(); people. add(new Person("Joe", 21)); people. add(new Person("Sue", 20)); class Person { private String name; private int age; public Person (String n, int a) { name = n; age = a; } Person student 1 = people. get(0); Person student 2 = people. get(1); } } }
// Java 1209. java // This program compiles and there is still no output. Output is not the // issue. Understanding the correct syntax involved does matter. // In this case lines 18 and 19 cast to the <Person> class, which makes // Java happy. Without casting the data types are unknown. import java. util. Array. List; class Person { private String name; private int age; public class Java 1209 { public static void main(String[] args) int a) { Array. List people = new Array. List(); people. add(new Person("Joe", 21)); people. add(new Person("Sue", 20)); } public Person (String n, { name = n; age = a; } Person student 1 = (Person) people. get(0); // Line 18 Person student 2 = (Person) people. get(1); // Line 19 } }
// Java 1210. java // Since Java Version 5. 0 the "casting" solution of the last program is so // "old Java version". It is now possible to specify, at the time that the // <Array. List> object is constructed, what kind of object is stored. // Note: the "unsafe operations" warning is now also gone. import java. util. Array. List; public class Java 1210 { public static void main(String[] args) { Array. List<Person> people = new Array. List<Person>(); class Person people. add(new Person("Joe", 21)); { people. add(new Person("Sue", 20)); Person student 1 = people. get(0); Person student 2 = people. get(1); } } int a) private String name; private int age; public Person (String n, { } name = n; age = a;
// Java 1211. java // This program shows another benefit of using generics. // There are two <Array. List> objects and both are constructed to store <Integer> // values. After three values are entered in the <numbers 1> object, those values are // then assigned to <numbers 2>, which works without problems. import java. util. Array. List; [100, 200, 300] public class Java 1211 { public static void main(String[] args) { Array. List<Integer> numbers 1 = new Array. List<Integer>(); numbers 1. add(new Integer(100)); numbers 1. add(new Integer(200)); numbers 1. add(new Integer(300)); System. out. println(numbers 1); Array. List<Integer> numbers 2 = new Array. List<Integer>(); numbers 2. add(numbers 1. get(0)); numbers 2. add(numbers 1. get(1)); numbers 2. add(numbers 1. get(2)); System. out. println(numbers 2); } }
// Java 1212. java // Generics make sure that an array is in fact an array. An array // is supposed to be a data structure with elements of the same type. // This program example - which does not use generics - allows the // list array to store three different data types. import java. util. Array. List; [3. 14159, 200, Dubrovnik] public class Java 1212 { public static void main(String[] args) { Array. List list = new Array. List(); list. add(new Double(3. 14159)); list. add(new Integer(200)); list. add(new String("Dubrovnik")); System. out. println(list); } } This violates the definition of an array.
// Java 1213. java // Once generics are used, Java becomes very picky. If you want to create // an <Array. List> object to store <Double> values, such as is shown below, // then only <Double> values must be added. The attempt to add one // <Double> and two <Integer> objects results in two errors. import java. util. Array. List; public class Java 1213 { public static void main(String[] args) { Array. List<Double> list = new Array. List<Double>(); list. add(new Double(3. 14159)); list. add(new Integer(200)); list. add(new Integer(300)); System. out. println(list); } }
// Java 1214. java // This program shows three ways to display the members of an <Array. List> object. // The enhanced <for. . each> loop works very well with <Array. List> objects. import java. util. Array. List; public class Java 1214 { public static void main(String[] args) { Array. List<String> names = new Array. List<String>(); names. add("Isolde"); names. add("John"); names. add("Greg"); names. add("Maria"); names. add("Heidi"); System. out. println(names); System. out. println(); for (int index = 0; index < names. size(); index++) System. out. println(names. get(index)); System. out. println(); } } for (String name: names) System. out. println(name); Isolde John Greg Maria Heidi
// Card. java 12 -26 -14 // This is the "unit" class that stores information about a single card. // *********************************** // The "Elevens" AP Lab is created for the College Board APCS // curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik. // Leon Schram has altered this "Elevens" AP Lab file to focus on // CS topics as the "Elevens" Lab is integrated into the curriculum. public class Card { private String suit; private String rank; private int value; public Card(String s, String r, int v) { suit = s; rank = r; value = v; } public String get. Suit() { return suit; } public String get. Rank() { return rank; } public int get. Value() { return value; } public boolean matches(Card other. Card) { return other. Card. get. Suit(). equals(this. suit) && other. Card. get. Rank(). equals(this. rank) && other. Card. get. Value() == this. value; } } public String to. String() { return "[" + suit + ", " + rank + ", " + value + "]"; }
// Deck 01. java 12 -26 -14 // This is the first stage of the Deck class, as introduced // in the previous "Static Arrays" chapter. // This version is implemented with "dynamic arrays". // ********************************** // The "Elevens" AP Lab is created for the College Board APCS // curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik. // Leon Schram has altered this "Elevens" AP Lab file to focus on // CS topics as the "Elevens" Lab is integrated into the curriculum. import java. util. Array. List; public class Deck 01 { private Array. List<Card> cards; private int size; public Deck 01() { cards = new Array. List<Card>(); ; size = 0; } public int get. Size() { return size; } } public boolean is. Empty() { return size == 0; }
// Deck. Tester 01. java 12 -26 -14 // This program tests the "dynamic array" Deck 01 class. // ********************************** // The "Elevens" AP Lab is created for the College Board APCS // curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik. // Leon Schram has altered this "Elevens" AP Lab file to focus on // CS topics as the "Elevens" Lab is integrated into the curriculum. public class Deck. Tester 01 { public static void main(String[] args) { Deck 01 deck = new Deck 01(); System. out. println(deck. get. Size()); System. out. println(deck. is. Empty()); } Deck 01@1 db 9742 } 0 true
// Deck 02. java 12 -26 -14 // Methods <add> and <display> are added to the <Deck 02> class. // Objects of the <Card> class can now be stored in the <cards> array. // This version is implemented with "dynamic arrays" // ********************************** // The "Elevens" AP Lab is created for the College Board APCS // curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik. // Leon Schram has altered this "Elevens" AP Lab file to focus on // CS topics as the "Elevens" Lab is integrated into the curriculum. public boolean is. Empty() import java. util. Array. List; { return size == 0; public class Deck 02 } { public void add(String suit, private Array. List<Card> cards; String rank, int value) private int size; { Card temp = public Deck 02() new Card(suit, rank, value); { cards. add(temp); cards = new Array. List<Card>(); size++; size = 0; } } public void display() { public int get. Size() for (Card card: cards) { System. out. println(card); return size; } } }
// Deck. Tester 02. java 12 -26 -14 // This program tests the <Deck 02> class. // This program tests the "dynamic array" Deck 02 class. // ********************************** // The "Elevens" AP Lab is created for the College Board APCS // curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik. // Leon Schram has altered this "Elevens" AP Lab file to focus on // CS topics as the "Elevens" Lab is integrated into the curriculum public class Deck. Tester 02 { public static void main(String[] args) { Deck 02 deck = new Deck 02(); deck. add("Clubs", "Three", 3); deck. add("Diamonds", "Four", 4); deck. add("Hearts", "Five", 5); deck. add("Spades", "Six", 6); deck. display(); System. out. println(deck. get. Size()); System. out. println(deck. is. Empty()); } } [Clubs, Three, 3] [Diamonds, Four, 4] [Hearts, Five, 5] [Spades, Six, 6] 4 false
// Deck 03. java 12 -26 -14 // The <display> method is now replaced by the <to. String> method. // This version is implemented with "dynamic arrays". // ********************************** // The "Elevens" AP Lab is created for the College Board APCS // curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik. // Leon Schram has altered this "Elevens" AP Lab file to focus on // CS topics as the "Elevens" Lab is integrated into the curriculum. import java. util. Array. List; public class Deck 03 { private Array. List<Card> cards; private int size; public Deck 03() { cards = new Array. List<Card>(); size = 0; } // all other methods are the same as Deck 02 } public String to. String() { String temp = ""; for (int k = 0; k < size; k++) temp = temp + cards. get(k). to. String() + "n"; return temp; }
// Deck. Tester 03. java 12 -26 -14 // This program tests the Deck 03 class. // This program tests the "dynamic array" Deck 03 class. // ********************************** // The "Elevens" AP Lab is created for the College Board APCS // curriculum by Michael Clancy, Robert Glen Martin and Judith Hromcik. // Leon Schram has altered this "Elevens" AP Lab file to focus on // CS topics as the "Elevens" Lab is integrated into the curriculum. public class Deck. Tester 03 { public static void main(String[] args) { Deck 03 deck = new Deck 03(); deck. add("Clubs", "Three", 3); deck. add("Diamonds", "Four", 4); deck. add("Hearts", "Five", 5); deck. add("Spades", "Six", 6); System. out. println(deck. get. Size()); System. out. println(deck. is. Empty()); } } [Clubs, Three, 3] [Diamonds, Four, 4] [Hearts, Five, 5] [Spades, Six, 6] 4 false
// Magpie 01. java 12 -26 -14 // This "Magpie" version looks only at the "negative" response // and considers all the different cases of a "no" substring. //******************************** // The "Magpie" AP Lab is created for the College Board APCS // curriculum by Laurie White. // Leon Schram has altered this "Magpie" file to focus on // CS topics as the "Magpie" Lab is integrated into the curriculum. public class Magpie 01 { public String get. Greeting() { return "Hello, let's talk. "; } public String get. Response(String statement) { String response = ""; if (statement. length() == 0) { response = "Say something, please. "; } else if (find. Keyword(statement, "no") >= 0) { response = "Why so negative? "; } else { response = "I don't know what to say"; } } return response;
private int find. Keyword(String statement, String goal, int start. Pos) { String phrase = statement. trim(); int psn = phrase. to. Lower. Case(). index. Of(goal. to. Lower. Case(), start. Pos); while (psn >= 0) { String before = " ", after = " "; if (psn > 0) { before = phrase. substring(psn - 1, psn). to. Lower. Case(); } if (psn + goal. length() < phrase. length()) { after = phrase. substring( psn + goal. length(), psn + goal. length() + 1). to. Lower. Case(); } if (((before. compare. To("a") < 0) || (before. compare. To("z") > 0)) && ((after. compare. To("a") < 0) || (after. compare. To("z") > 0))) { return psn; } psn = phrase. index. Of(goal. to. Lower. Case(), psn + 1); } } } return -1; private int find. Keyword(String statement, String goal) { return find. Keyword(statement, goal, 0); }
// Magpie. Tester 01. java 12 -26 -14 // This program tests the Magpie 01 class. // ******************************** // The "Magpie" AP Lab is created for the College Board APCS // curriculum by Laurie White. // Leon Schram has altered this "Magpie" file to focus on // CS topics as the "Magpie" Lab is integrated into the curriculum. import java. util. Scanner; public class Magpie. Tester 01 { public static void main(String[] args) { Magpie 01 maggie = new Magpie 01(); System. out. println (maggie. get. Greeting()); Scanner in = new Scanner (System. in); String statement = in. next. Line(); } } while (!statement. equals("Bye")) { System. out. println (maggie. get. Response(statement)); statement = in. next. Line(); }
// Magpie 02. java 12 -26 -14 // This Magpie version provides the following responses: // 1. "Why so negative" when substring "no" is found. // (This is the simplistic version for any "no" anywhere) // 2. "Tell me more about your family" when relatives are found. // 3. Otherwise one of four random responses is provided. //******************************** // The "Magpie" AP Lab is created for the College Board APCS curriculum by Laurie White. // Leon Schram has altered this "Magpie" file to focus on // CS topics as the "Magpie" Lab is integrated into the curriculum. public class Magpie 02 { public String get. Greeting() { return "Hello, let's talk. "; } public String get. Response(String statement) { String response = ""; if (statement. index. Of("no") >= 0) { response = "Why so negative? "; } else if (statement. index. Of("mother") >= 0 || statement. index. Of("father") >= 0 || statement. index. Of("sister") >= 0 || statement. index. Of("brother") >= 0) { response = "Tell me more about your family. "; } else { response = get. Random. Response(); } return response; }
private String get. Random. Response() { final int NUMBER_OF_RESPONSES = 4; double r = Math. random(); int which. Response = (int)(r * NUMBER_OF_RESPONSES); String response = ""; } } if (which. Response == 0) { response = "Interesting, tell me more. "; } else if (which. Response == 1) { response = "Hmmm. "; } else if (which. Response == 2) { response = "Do you really think so? "; } else if (which. Response == 3) { response = "You don't say. "; } return response;
// Magpie. Tester 02. java 12 -26 -14 // This program tests the Magpie 02 class. // ******************************** // The "Magpie" AP Lab is created for the College Board APCS // curriculum by Laurie White. // Leon Schram has altered this "Magpie" file to focus on // CS topics as the "Magpie" Lab is integrated into the curriculum. import java. util. Scanner; public class Magpie. Tester 02 { public static void main(String[] args) { Magpie 02 maggie = new Magpie 02(); System. out. println (maggie. get. Greeting()); Scanner in = new Scanner (System. in); String statement = in. next. Line(); } } while (!statement. equals("Bye")) { System. out. println (maggie. get. Response(statement)); statement = in. next. Line(); }
- Slides: 50