简体   繁体   English

ArrayList 的字符串作为参数并返回列表中的最后一项

[英]ArrayList of Strings as a parameter and return the last item in 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.我需要在 Java 中编写此函数的帮助。我完全陷入了一个函数:字符串的 ArrayList 作为参数并返回列表中的最后一项。

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.您可以通过 ArrayList 类的预定义方法访问它们。

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM