230 likes | 240 Views
Get a comprehensive review of Java libraries, packages, ArrayList class, ArrayList syntax, for-each loops, polymorphism, and using List interface for ArrayList and LinkedList. Learn to use ArrayList effectively and understand how to restrict values using generics.
E N D
Correction to yesterday’s slides: • I wrote, “Methods in an interface must be public.” • This is more accurate: “Methods in an interface cannot be private.”
Review: libraries and packages • In Java, a library is a group of packages. • A package is a group of classes that belong together. • For example, the java.lang package (lang is a package inside the java library) is the most used package, and provides classes that are fundamental to the language, such as String and Object. • Another very useful package is java.util. • It is possible to create your own package, although that is not part of the AP curriculum.
What if a method has no visibility modifier? • Sometimes you will see a method that is neither private nor public, such as: void displayNum() { System.out.println(x); } • This is called a package protected method • This method can only be called by: • Other methods in the same class • Other classes in the same package • This method cannot be called by any subclasses.
The ArrayList Class • The ArrayList class is part of the java.util package • An ArrayList is like an array, but it automatically grows and shrinks as elements are added or deleted (so, there are never ANY empty elements in an ArrayList) • Items can be inserted or removed with a single method call • It stores references to the Object class, which allows it to store ANY kind of object – so, you can store different types in the same array
However, this means that you cannot store primitive types (int, double, char, boolean) in an ArrayList. Instead, you would store their Wrapper Class equivalents: • Integer • Double • Character • Boolean
ArrayList Syntax • Import java.util.ArrayList • ArrayList is a class, so you must instantiate an object of it • If you want to add an object (such as a String) to an ArrayList, there is no special syntax. However, if you want to add a “primitive type” (such as int, double, char), you must add using a wrapper class. Commonly used ArrayList methods: • add (obj) // adds obj at the end of the list • add (index, obj) // adds obj at the specified index • set (index, obj) // replaces the value at the specified index with obj • get (index) // returns the object at the specified index • indexOf(obj) // finds the index of the specified obj • remove (index) // deletes the object at the specified index • size ( ) // returns the size of the ArrayList • Demo: ArrayListDemo
Unboxing • “Unboxing” means taking an Integer object and assigning its value to a primitive int. • This is done using the .intValue( ) method. • Example; Integer z = new Integer(7); // box int y = z.intValue( ); // unbox • This is what we saw in the demo, when accessing an integer that is stored in an ArrayList. (See ArrayListDemo.)
When using an ArrayList, you might get this compiler message: filename uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. • This is just a warning, not an actual error. You can ignore it.
for-each loops are often used with ArrayLists. • Open ForEachLoopDemo
Polymorphism is commonly seen when using ArrayList. • ArrayList is a class that implements the List interface. The List interface is a blueprint for its “implementor” classes. • There is another implementor of the List interface, called LinkedList, that you do not have to know about, but it helps to be aware of it. • LinkedList is similar to ArrayList. It “performs better” than ArrayList when using the addand removemethods, but worse than ArrayList when using the getand setmethods. • So, if you plan on inserting/deleting a lot of elements from a list of objects, LinkedList is preferable. If you just plan on retrieving elements from a list, ArrayList is better.
Unlike LinkedList, you do need to be aware of the List interface. Often, you will see ArrayLists declared this way: List x; • And then, later on: x = new ArrayList(); • Alternatively: you might see this: List x = new ArrayList(); • Or, a later line of code might want to change x to be a LinkedList, like this: x = new LinkedList(); • If x had been declared as an ArrayList originally, this would be a problem. You would have to go back and change a lot of code in order to do this. Using polymorphism here will save you a lot of time. • Note: we learned previously that an interface cannot be instantiated. In this example, we are not instantiating List; we are actually instantiating ArrayList. • Remember that since List is an interface, its methods are empty. They don’t actually do anything. The whole point of using List is that you can easily switch back and forth from ArrayList to LinkedList by using polymorphism.
Restricting the values in an Arraylist • By default, an ArrayList can store any type of Object. • You can, if you wish, restrict the type of thing that an ArrayList can hold, by using the < > symbols. This is called using generics. • Examples: 1) ArrayList<Person> z = new ArrayList<Person>(); 2) ArrayList<Integer> x = new ArrayList<Integer>(); 3) List<String> a; a = new ArrayList<String>();
Why use generics? • Simply put, using generics will make your code more “stable” by catching more errors at compile time rather than at run-time. • Compiler errors are usually easier to fix than runtime errors. • When the compiler knows that an ArrayList is restricted to holding Strings, for example, it can check your code before running the program to find any errors that specifically involve using Strings. • Another benefit of using generics in an ArrayList is that it eliminates the need for type casting. • Example: ArrayList<Integer> nums = new ArrayList<Integer>(); nums.add(23); nums.add(11); // no need for “new Integer (11)” etc
Another example: public class Sample { private ArrayList<Comparable>; // more code here } • In this class, a private instance variable is created – it is an Arraylist. • But note that it will NOT hold objects of the Comparable interface, because that is not valid. An interface cannot be instantiated. • Instead, it will hold objects that implement the Comparable interface.
Review: static methods • A static method can be called without having to create an object. • It is called directly by using the class name (example: SavitchIn.readLine( ) ) • It makes sense to make a method static when that method doesn’t have to be unique for each object that calls it. • Demo: StaticMethodClass, StaticMethodClient
Static variables • A variable can also be declared with the keyword static. • Just like a static method, a static variable is not accessed through an object. It is accessed by using the name of the class itself. • Why use a static variable? When that variable is not unique to each object of the class; when it is the same for all objects of the class. • Now we know where instance variables get their name: they are unique for every instance (every object) of the class. • A static variable is also known as a class variable. • Demo: StaticVariableClass & StaticVariableClient
Assignment(NamesArray) • Ask the user how many names they will enter. • Then ask for those names, storing them in an ArrayList. Display the list. • Ask the user to choose one of the names. Delete this person from the list. Display the list. • Insert your own name so that it’s the 2nd name in the list. Display the list. • Then add the name “Mike Gordon” to the end of the list. Display the list. • Then, ask the user to choose another name to delete, as well as what name will replace it. Replace the name. Display the list. • Then, ask how old each person on the list is (ex: “How old is Mike Gordon?”). Insert each person’s age immediately after that person’s name in the List. Display the list.