Lecture 7 - Interfaces, Generics & ArrayLists Flashcards

1
Q

What are interfaces? Why are they useful?

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
What happens if you store an object as an interface reference?
Eg. Interface a = new OtherClass();
A

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:

  1. The Greeter interfaces methods
  2. toString method
  3. getClass

None of their own methods

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does a class implement an interface?

A

public class Dog implements Greeter{..

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you create an interface class?

A

public class interface Greeter{

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What methods do a class that implements an interface need to have?

A

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)

  1. constructor
  2. toString()
  3. getter
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Give an example of using the Random import to find the next number and put it into each position in the array.

A
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] + " ");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

When is System.out.println(); useful?

A

Are a loop to add it and then below when we do another print statement it will be on the next line.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How can we call a sort method from another class and use it for an array we made in the current class?

A

ClassName.methondname(array name)

Eg., Sorting.sort(a);

from the lecture example (8)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does r.nextDouble() do?

A

Returns the next random double number between 0.0 and 1.0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What happens when a user clicks something on a Swing GUI?

A

an ActionEvent is created automatically and is processed by a method called actionPerformed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you use an ActionListener?

A
  1. Implements ActionListener in the class name
  2. Register the component with the Listener:
    component. addActionListener(instanceOfListenerclass)
  3. Override the actionPerformed(Action Event e) method
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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?

A

Generics

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Comparable is a good example of generics. What does it look like?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you write methods that can take arguments of any type?

A

Use eg.,

public static void printArray(G[] Array)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is an ArrayList?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you insert an element at a specified position?

A
// insert element at specified pos
public void add(int index, E element)

languages.add(1, “C++”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you add an element to the end of an array list?

A
// 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);  
 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What method removes all of the elements from an ArrayList?

A

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(): []

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What method returns true if the list contains a specific element?

A

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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What method returns the element at a specified position in the list?

A

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);  
        }  
    }  
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What method is used to remove an element at a specified index from ArrayList.

A

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

22
Q

Give an example of how you would create an ArrayList object called cars that will store strings?

A

import java.util.ArrayList;

ArrayList cars = new ArrayList();

23
Q

Given an example of how you would create an ArrayList object of the type of another class called Person?

A

import java.util.ArrayList;

ArrayList *CLASS TYPE * cars = new ArrayList CLASS TYPE();

*** should have class type names

24
Q

What is the syntax for a for each loop?

A
for(Type var:array){  
//code to be executed  
}
25
Q

Give an example of a for each loop with an array?

A

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);  
   }  
 }   
}
26
Q

Give an example of using a for each loop in an Integer ArrayList?

A

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);

27
Q

When there are no shared attributes between different classes what is a sensible way of setting up the program?

A

Using interfaces, not inheritance

28
Q

How would you shrink an object?

A

Multiply it by a number less than 1.

29
Q

Give an example of polymorphism being used in interfaces?

A

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);
30
Q

When should you use interfaces rather than inheritance?

A

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)

31
Q

What does this do from lab question?

this.add(new FilledPanel(6UNIT,3UNIT,1UNIT,3UNIT, Color.gray,Color.DARK_GRAY));

A

** look it up

32
Q

How do you define generics?

A
// 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()); 
    } 
}
33
Q

How does generics work?

A
  1. You use in the class name
  2. Need to specify the type of objects
    eg. , Container obj = new Contain<>();
    * * NOTE classes Integer etc.. NOT int
  3. You will use getters & setters
34
Q

What are three advantages of Generics?

A
  1. Type-safety
  2. Don’t need type casting
  3. It is checked at compile time so problem will not occur at run time.

https://www.javatpoint.com/generics-in-java

35
Q

Predict the output of this generics statement (check in eclipse)

A

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 );   
}    }
36
Q

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”)

A

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.

37
Q

What error will this give us?

ArrayListInteger list = new ArrayListInteger();

list. add(“hello”);
list. add(32);

A

A compile-time error because it is a type String but we are adding an int.

38
Q

What errors are in this generics code?

import java.util.;
class TestGenerics1{
public static void main(String args[]){
ArrayList String list=new ArrayList
String*();
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());  
}  
}  
}
A
  1. list.add(32) gives a compile time error because it is an int, not a String.
  2. String s=list.get(1); type casting is not required
39
Q

Give an example of a for each loop with an arraylist

A
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

40
Q

What denotes a generic?

A

Any char like E or T within a less than and greater than signs

41
Q

What does a generic comparable interface look like?

A

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

42
Q

What does a generic method look like?

What is G saying to Java?

A
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] + " ");	}}
43
Q

What does a generic class look like?

A

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

44
Q

How do you return an element at a specified position in an ArrayList?

A

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);}}

45
Q

How do you check if an arrayList is empty?

A

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

46
Q

How do you return the number of elements in the ArrayList?

A

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

47
Q

How do you remove a specified element from an ArrayList?

A

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]

48
Q

How do you remove the element at a specified index

from an ArrayList?

A

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

49
Q

What is useful about an arraylist?

A

It grows and shrinks as you use it!

50
Q

What types goes in the arraylist.

A

Wrapper classes ie.

Integer
String
Double 
Character
Boolean
Class name ie., Book

Converts primitive types!

51
Q

How do you create an arraylist of type class?

A
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);  
    }  
}  
}