To create a method that takes an array as an argument, you would do this:

public static void printAges(int[] age) { // prints ages to screen
    for (int x = 0; x < age.length; x++) {
        System.out.println("Age: " + age[x]);

How would you create a method like this one with one exception, that it takes an array list as an argument instead of an array?

Thanks. -- Krishna

  • This belongs on StackOverflow. Hint: int[] is the name of a type, and ArrayList<int> is the name of a different type. – Caleth Aug 31 '17 at 22:18
  • I'll move the question to Stack Overflow. @Caleth – Krish Aug 31 '17 at 22:20
  1. Best practices would have you generalize the argument such that instead of working with the concrete class ArrayList you would work with an abstracted interface, here, List. This way you would be able to reuse this implementation for every class that supports List, not just ArrayList.

  2. You are looping over the array using a byte loop control variable. This is rather unusual (i.e. error prone). FYI, there is no performance gain for byte-typed variable over a more expected int type. The byte type will begin to fail with numbers larger than 7 bits (e.g. 128). Suggest you use the int type for integral loop control and indexing variables.

  3. There are good alternatives to using looping based on incrementing an integer. foreach is one construct, and lambdas are another. These constructs will work better across the broad set of classes that implement the List interface. The foreach construct uses an iterator, which is easy to use and under the covers is specialized by the specific collection being used. The lambda approach uses a map-style operation where you supply a function to be invoked on each element, leaving the iteration totally out of your code. Lambda's support composition, so you can filter before mapping, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.