ArrayList Worksheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Java Name - justin smith

ArrayList worksheet #1

1. Write a method named findPosition that accepts two parameters, an int named keyValue and an array list of
Integer's named list. The method must return the first subscript position within list in which keyValue is found. If
keyValue is not stored in list, return the value -1.
Example#1: keyValue = 3 & list = {4, 8, 3, 2, 3} 2 would be returned
Example#2: keyValue = 5 & list = {4, 8, 3, 2, 3} -1 would be returned

public static int findPosition(int keyValue, ArrayList<Integer> list)


{
public class hiphop {
public static int findPosition(int keyValue, ArrayList<Integer> list) {
for(int i=0; i<list.size(); i++) {
if(list.get(i)==keyValue) {
return 1;
}
}
return -1;
}
public static void main(String[] args) {
ArrayList<Integer> problem1 = new ArrayList<Integer>();

problem1.add(4);
problem1.add(8);
problem1.add(3);
problem1.add(2);
problem1.add(3);
System.out.println(findPosition(8, problem1));

2. Write a method named countMales that accepts an array list parameter named list that contains strings. The method must
count up and return the number of times that the string “male” is found in list.
Example: list = {"female", "male", "male", "female", "male"} 3 would be returned

public static int countMales(ArrayList<String> list)


{
public static int countMales(ArrayList<String> list) {
int count = 0;

return count;

ArrayList<String> problem2 = new ArrayList<String>();


problem2.add("female");
problem2.add("male");
problem2.add("male");
problem2.add("female");
problem2.add("male");

System.out.println(countMales(problem2));
}

3. Write a method named parseIntoArrayList that accepts a string parameter named input. The method must break
input up into individual letters & store each letter into an ArrayList of strings that is instantiated as a local variable. The new
ArrayList must then be returned.
Example: input = "Wyomissing" return the ArrayList {"W", "y", "o", "m", "i", "s", "s", "i", "n", "g"}

public static ArrayList<String> parseIntoArrayList(String input)


{
public static ArrayList<String> parseIntoArrayList(String input){
ArrayList<String> output = new ArrayList<String>();

return output;
}

ArrayList<String> problem3 = new ArrayList<String>();

problem3.add("w");
problem3.add("y");
problem3.add("o");
problem3.add("m");
problem3.add("i");
problem3.add("s");
problem3.add("s");
problem3.add("i");
problem3.add("n");
problem3.add("g");

System.out.println(problem3);

You might also like