0

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.

  • 1
    Have you tried anything?? please add the code. – Kaustubh Khare Dec 04 '19 at 06:46
  • Where did you look before? What have you tried before? What didn't workout as expected and why? Hint: For your second question check the documentation of ArrayList. – Nicktar Dec 04 '19 at 06:46
  • can you post what you have tried? – Himanshu Singh Dec 04 '19 at 06:46
  • Pleare read through ArrayList documentation: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html. If you tried anything and encounter an error, please put it in your question – NothingBox Dec 04 '19 at 06:48
  • Does this answer your question? [How to get the last value of an ArrayList](https://stackoverflow.com/questions/687833/how-to-get-the-last-value-of-an-arraylist) – M. Justin Jul 27 '23 at 04:01

3 Answers3

1

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
}
Cyrille Con Morales
  • 918
  • 1
  • 6
  • 21
0
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();
}
Lebanner
  • 38
  • 1
  • 8
  • While this code may answer the question, providing additional context regarding *why* and/or *how* this code answers the question improves its long-term value. – Tân Dec 04 '19 at 07:44
0

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();
}
Naveen Avidi
  • 3,004
  • 1
  • 11
  • 23