@DavidMcConnachi/

CSE110_Java_ArrayList_as_Arguments_Example

Java

No description

fork
loading
Files
  • Main.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    // declare and instantiate the ArrayList of Cat
    ArrayList<Cat> cats = new ArrayList<Cat>();

    Cat my_cat;

    // add three cats to the list
    my_cat = new Cat("Chichi");
    cats.add(my_cat);
    my_cat = new Cat("Alfi");
    cats.add(my_cat);
    my_cat = new Cat("Benny");
    cats.add(my_cat);

    // call a method that take an ArrayList as an argument
    Cat first_cat = find_first(cats);
    System.out.println("first cat: " + first_cat.name);
    }

  static Cat find_first(ArrayList<Cat> my_cats) {
    Cat first_cat = my_cats.get(0);
    for (Cat some_cat : my_cats) {
      if (some_cat.name.compareTo(first_cat.name) < 0) {
        first_cat = some_cat;
      }
    }

    return first_cat;
  }
}

class Cat {
	String name;
	
	Cat(String init_name) {
		name = init_name;
	}
	
	void print() {
		System.out.println(name + " says 'Meow!'");
	}
}