I need help on writing this function in Java.. I'm completely stuck A function: ArrayList of Strings as a parameter and return the last item in the list.
And I need an function: Arraylist of Strings as a parameter and return the size of the list.
I need help on writing this function in Java.. I'm completely stuck A function: ArrayList of Strings as a parameter and return the last item in the list.
And I need an function: Arraylist of Strings as a parameter and return the size of the list.
Giving you an idea and example
import java.util.ArrayList; // import the ArrayList class
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
For getting the last item
String lastItem(){
return cars.get(cars.size()-1); //will give you Ford
}
For getting the size
int numberOfCars(){
return cars.size();//will give you 3
}
public String getLastItemFromList(ArrayList<String> al) {
if(al.isEmpty()) {
return "";
}
return al.get(al.size()-1);
}
public int getSizeOfList(ArrayList<String> al) {
return al.size();
}
Y u need separate methods ? You can access them by predefined methods of the ArrayList class.
As of what I understood, here is my help !
//return Last element
ArrayList<String> stringsList; //assign values
String getLastItem(ArrayList<String> list){
return list.get(list.size()-1);
}
//return size of the list
int getSize(ArrayList<String> list){
return list.size();
}