Lecture 7 - Interfaces, Generics & ArrayLists Flashcards
What are interfaces? Why are they useful?
- Interfaces are a collection of abstract methods (“bare bones”), but have no implementations, constructors and don’t return anything.
- A class that implements an interface must include the methods from the interface, but the interface doesn’t care what’s actually inside them.
- Interfaces are useful when you want to implement certain functionality, but there are no shared attributes.
- Any objects from a class that implements an interface can be stored in a reference of the type of the interface
What happens if you store an object as an interface reference? Eg. Interface a = new OtherClass();
You can only use the methods from the interface class. Greeter is the interface, person & dog implement the interface
Person p = new Person("Sam", 45); Greeter a = new Person("Mary", 34); Greeter b = new Dog();
Greeter[] aa = new Greeter[3]; aa[0] = new Dog(); aa[1] = new Dog(); aa[2] = new Person("Jill",17);
// call sayHello() from Greeter for each position in the array for(int i=0;i<3;i++) { aa[i].sayHello(); }
Now the only methods they can access are:
- The Greeter interfaces methods
- toString method
- getClass
None of their own methods
How does a class implement an interface?
public class Dog implements Greeter{..
How do you create an interface class?
public class interface Greeter{
What methods do a class that implements an interface need to have?
The method from the interface class (interface doesn’t care what’s in it as long as it returns the correct type eg., boolean result)
- constructor
- toString()
- getter
Give an example of using the Random import to find the next number and put it into each position in the array.
Number[] a = new Number[10]; Random r = new Random(); System.out.println("Unsorted");
for(int i=0;i<10;i++) { a[i] = new Number(r.nextInt(100)); System.out.print(a[i] + " ");
When is System.out.println(); useful?
Are a loop to add it and then below when we do another print statement it will be on the next line.
How can we call a sort method from another class and use it for an array we made in the current class?
ClassName.methondname(array name)
Eg., Sorting.sort(a);
from the lecture example (8)
What does r.nextDouble() do?
Returns the next random double number between 0.0 and 1.0
What happens when a user clicks something on a Swing GUI?
an ActionEvent is created automatically and is processed by a method called actionPerformed
How do you use an ActionListener?
- Implements ActionListener in the class name
- Register the component with the Listener:
component. addActionListener(instanceOfListenerclass) - Override the actionPerformed(Action Event e) method
instanceOf is a clumsy way of doing things because it can take any object, we need to check it is the right object.
What is a better way of doing it?
Generics
Comparable is a good example of generics. What does it look like?
Compares this Object with the specified Object for order. Returns a -1 if the current object should be earlier, 0 if it is in the same place, or 1 if the current should object should be later than the earlier object in the list.
public class Student2 implements Comparable{ private int grade; private String name;
public Student2(String n,int g) { name = n; grade = g;}
public int getGrade() {
return grade;}
public int compareTo(Student2 o) { if(this.getGrade() > o.getGrade()) { return 1;} else if(this.getGrade() < o.getGrade()) { return -1; }else {return 0; }}}
How do you write methods that can take arguments of any type?
Use eg.,
public static void printArray(G[] Array)
What is an ArrayList?
An object we can use to store references to store objects - (not primitive types, but you can get around that using the wrapper class!). That can grow & shrink based on the number of elements. It is generic so we need to tell it what type we will store in it.
How do you insert an element at a specified position?
// insert element at specified pos public void add(int index, E element)
languages.add(1, “C++”);
How do you add an element to the end of an array list?
// add element to the end of specified type 'E' public boolean add(E e)
//Creating a list of numbers List list2=new ArrayList(); list2.add(21); list2.add(11); list2.add(51); list2.add(1);
//Sorting the list Collections.sort(list2);
//Traversing list through the for-each loop for(Integer number:list2) System.out.println(number); }
What method removes all of the elements from an ArrayList?
arrayListName.clear();
eg.,
ArrayList languages = new ArrayList<>();
languages.add(“Java”);
languages.add(“JavaScript”);
languages.add(“Python”);
System.out.println(“Programming Languages: “ + languages);
// remove all elements languages.clear(); System.out.println("ArrayList after clear(): " + languages); } }
Programming Languages: [Java, JavaScript, Python]
ArrayList after clear(): []
What method returns true if the list contains a specific element?
public boolean contains(Object o)
arrayListName.contains());
eg., import java.util.ArrayList;
class Main { public static void main(String[] args) { // create an ArrayList ArrayList numbers = new ArrayList<>();
// insert element to the arraylist numbers. add(2); numbers. add(3); numbers. add(5);
// returns true number.contains(3)
// returns false number.contains(1)
What method returns the element at a specified position in the list?
public E get(int index)
- This is the get() for an Array list.
- Throws an IndexOutOfBounds Exception
Eg, import java.util.LinkedList; import java.util.List; public class JavaListGetExample1 { public static void main(String[] args) { List list= new LinkedList<>(); for (int i=0;i<6;i++){ list.add(i); // returns the element at the specified position in this list int index =list.get(i); System.out.println("Element "+i+" stored at Index : "+index); } } }
What method is used to remove an element at a specified index from ArrayList.
public E remove(int index)
It shifts any subsequent elements to the left (subtracts one from their indices).
Eg., ArrayList *class type* color_list = new ArrayList *class type* (7); color_list.remove(2);
*LESS THAN SIGN DOESN’T WORK ON THIS or GREATER THAN BUT SHOULD ALWAYS HAVE THE CLASS TYPE NAME IN BETWEEN THE GREATER THAN AND LESS THAN AFTER ARRAY LIST ON EACH SIDE
Give an example of how you would create an ArrayList object called cars that will store strings?
import java.util.ArrayList;
ArrayList cars = new ArrayList();
Given an example of how you would create an ArrayList object of the type of another class called Person?
import java.util.ArrayList;
ArrayList *CLASS TYPE * cars = new ArrayList CLASS TYPE();
*** should have class type names
What is the syntax for a for each loop?
for(Type var:array){ //code to be executed }
Give an example of a for each loop with an array?
lass ForEachExample1{
public static void main(String args[]){
//declaring an array int arr[]={12,13,14,44};
//traversing the array with for-each loop for(int i:arr){ System.out.println(i); } } }
Give an example of using a for each loop in an Integer ArrayList?
ArrayList missing info her myList = new ArrayList missing info here();
int sum2 = 0;
for(int i : myArray) sum2+=i;
System.out.println(“The array sum is “ + sum2);
When there are no shared attributes between different classes what is a sensible way of setting up the program?
Using interfaces, not inheritance
How would you shrink an object?
Multiply it by a number less than 1.
Give an example of polymorphism being used in interfaces?
Storing an object in a reference of the interface class
eg., Shape is the interface
Circle implements the interface
Shape[] shapes = new Shape[5]; shapes[0] = new Circle(10,10,20);
When should you use interfaces rather than inheritance?
You can implement interfaces as many times as you want, but you can only extend 1 other class using inheritance (ie., if shape is the abstract class & circle extends it, circle can’t extend anything else)
What does this do from lab question?
this.add(new FilledPanel(6UNIT,3UNIT,1UNIT,3UNIT, Color.gray,Color.DARK_GRAY));
** look it up
How do you define generics?
// We use greater than & equals to to specify Parameter type class Test*T* { // An object of type T is declared T obj; Test(T obj) { this.obj = obj; } // constructor public T getObject() { return this.obj; } }
// Driver class to test above class Main { public static void main (String[] args) {
// instance of Integer type Test iObj = new Test(15); System.out.println(iObj.getObject());
// instance of String type Test *String* sObj = new Test*String*("GeeksForGeeks"); System.out.println(sObj.getObject()); } }
How does generics work?
- You use in the class name
- Need to specify the type of objects
eg. , Container obj = new Contain<>();
* * NOTE classes Integer etc.. NOT int - You will use getters & setters
What are three advantages of Generics?
- Type-safety
- Don’t need type casting
- It is checked at compile time so problem will not occur at run time.
https://www.javatpoint.com/generics-in-java
Predict the output of this generics statement (check in eclipse)
public class TestGenerics4{
public static *E * void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { ‘J’, ‘A’, ‘V’, ‘A’, ‘T’,’P’,’O’,’I’,’N’,’T’ };
System.out.println( "Printing Integer Array" ); printArray( intArray ); System.out.println( "Printing Character Array" ); printArray( charArray ); } }
What error would this code give?
ArrayListInteger list = new ArrayListInteger();
list.add(10);
list.add(“10”);
With Generics, it is required to specify the type of object we need to store.
List list = new ArrayList();
list.add(10);
list.add(“10”)
Compile time error because the type is of class Integer but passing a “String”
In generics we need to specify the type we want to store.
What error will this give us?
ArrayListInteger list = new ArrayListInteger();
list. add(“hello”);
list. add(32);
A compile-time error because it is a type String but we are adding an int.
What errors are in this generics code?
import java.util.;
class TestGenerics1{
public static void main(String args[]){
ArrayList String list=new ArrayListString*();
list.add(“rahul”);
list.add(“jai”);
list.add(32);
String s=list.get(1);
System.out.println(“element is: “+s);
Iterator itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
- list.add(32) gives a compile time error because it is an int, not a String.
- String s=list.get(1); type casting is not required
Give an example of a for each loop with an arraylist
import java.util.*; class ForEachExample2{ public static void main(String args[]){ //Creating a list of elements ArrayList*String* list=new ArrayList*String*(); list.add("vimal"); list.add("sonoo"); list.add("ratan"); //traversing the list of elements using for-each loop for(String s:list){ System.out.println(s); } } }
Replace * with less than or greater than
What denotes a generic?
Any char like E or T within a less than and greater than signs
What does a generic comparable interface look like?
Comparable interface is mainly used to sort the arrays (or lists) of custom objects.
Lists (and arrays) of objects that implement Comparable interface can be sorted automatically by Collections.sort (and Arrays.sort).
public interface ComparableE {
public int compareTo(E o);}
E is like a “placeholder” which tells Java that there will be some type here that you define when you implement it eg., Student
What does a generic method look like?
What is G saying to Java?
public static *G* void printArray(G[] array) { // Prints an array of *G* objects for(int i=0;i*array.length;i++) { System.out.print(array[i] + " "); }}
What does a generic class look like?
public class GenericClass E {
E firstAttribute;
E secondAttribute;
public GenericClass(E f, E g) { firstAttribute = f; secondAttribute = g; }
public String toString(){
return( firstAttribute + “,\n” + secondAttribute);
}}
Generic type E for class, instance variables, variables passed to the instructor.
Note the toString assumes that its type E
How do you return an element at a specified position in an ArrayList?
arraylist.get(int index)
eg.,
ArrayListInteger numbers = new ArrayList<>();
numbers.add(22);
numbers.add(13);
numbers.add(35);
System.out.println(“Numbers ArrayList: “ + numbers);
int element = numbers.get(2); // return element at position 2
System.out.println(“Element at index 2: “ + element);}}
How do you check if an arrayList is empty?
arraylist.isEmpty()
eg.,
ArrayListString languages = new ArrayList**();
System.out.println(“Newly Created ArrayList: “ + languages);
// checks if the ArrayList has any element boolean result = languages.isEmpty(); // true System.out.println("Is the ArrayList empty? " + result);
languages.add(“Python”);
languages.add(“Java”);
System.out.println(“Updated ArrayList: “ + languages);
// checks if the ArrayList is empty result = languages.isEmpty(); // false System.out.println("Is the ArrayList empty? " + result);}}
Newly Created ArrayList: []
Is the ArrayList empty? true
Updated ArrayList: [Python, Java]
Is the ArrayList empty? false
How do you return the number of elements in the ArrayList?
arraylist.size()
ArrayList*String* languages = new ArrayList**(); // insert element to the arraylist languages.add("JavaScript"); languages.add("Java"); languages.add("Python"); System.out.println("ArrayList: " + languages);
// get the number of elements of arraylist int size = languages.size(); System.out.println("Length of ArrayList: " + size); }}
ArrayList: [JavaScript, Java, Python]
Length of ArrayList: 3
How do you remove a specified element from an ArrayList?
You can remove the specified element
arraylist.remove(Object obj)
import java.util.ArrayList;
class Main { public static void main(String[] args) { // create an ArrayList ArrayList*String* languages = new ArrayList**();
// insert element to the arraylist languages.add("JavaScript"); languages.add("Java"); languages.add("Python"); System.out.println("ArrayList: " + languages);
// remove the element Java boolean result = languages.remove("Java"); System.out.println("Is element Java removed? " + result); System.out.println("ArrayList after remove(): " + languages); } }
ArrayList: [JavaScript, Java, Python]
Is element Java removed? true
ArrayList after remove(): [JavaScript, Python]
How do you remove the element at a specified index
from an ArrayList?
arraylist.remove(int index)
import java.util.ArrayList;
class Main { public static void main(String[] args) { // create an ArrayList ArrayList*String*languages = new ArrayList**();
// insert element to the arraylist languages.add("JavaScript"); languages.add("Java"); languages.add("Python"); System.out.println("ArrayList: " + languages);
// remove the element from position 2 String element = languages.remove(2); System.out.println("ArrayList after remove(): " + languages); System.out.println("Removed Element: " + element); } }
ArrayList: [JavaScript, Java, Python]
ArrayList after remove(): [JavaScript, Java]
Removed Element: Python
What is useful about an arraylist?
It grows and shrinks as you use it!
What types goes in the arraylist.
Wrapper classes ie.
Integer String Double Character Boolean Class name ie., Book
Converts primitive types!
How do you create an arraylist of type class?
import java.util.*; class Book { int id; String name,author,publisher; int quantity; public Book(int id, String name, String author, String publisher, int quantity) { this.id = id; this.name = name; this.author = author; this.publisher = publisher; this.quantity = quantity; } } public class ListExample5 { public static void main(String[] args) { //Creating list of Books List list=new ArrayList(); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to list list.add(b1); list.add(b2); list.add(b3); //Traversing list for(Book b:list){ System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); } } }