methods - Why should we use a List of a particular type in Java -
i going through lesson in java, , lesson covers passing arraylist
object through static method. in first static method, see arraylist
had declared arraylist
, , name it. first static method displays of elements in array. second static method changes elements of arraylist
. when declaring arraylist
in method, must declared arraylist<integer>
modification purposes. why way, , why make difference? thank willing shed light on this.
import java.util.arraylist; public class chap11part5 { public static void main(string[] args) { arraylist<integer> numbers = new arraylist<integer>(); //for-loop create elements arraylist (int = 1; < 11; ++i) numbers.add(i); display(numbers); //display elements change(numbers, 5); //change elements (see "change" method) display(numbers); //display new results } //loop display elements of arraylist static void display(arraylist arr) { for(int = 0; < arr.size(); ++i) system.out.print(arr.get(i) + " "); system.out.println(); } //loop change elements of arraylist static void change(arraylist<integer> arr, int amount) { int value; for(int = 0; < arr.size(); ++i) { value = arr.get(i); arr.set(i, value + amount); } } }
the <>
syntax called generics - allows limit type of elements collection holds, , refer them type. it's not required, it's more convenient.
for instance, write second method without generics specified, you'd have handle casting yourself:
static void change(arraylist arr, int amount) { int value; for(int = 0; < arr.size(); ++i) { value = (integer) arr.get(i); // explicit casting here. yuck! arr.set(i, value + amount); } }
Comments
Post a Comment