在 Python 中有一个名为“列表”的数据结构。通过在 Python 中使用“列表”数据结构,我们可以追加、扩展、插入、删除、弹出、索引、计数、排序、反向。
Java 中有没有类似的数据结构可以让我们获得像 Python List 这样的所有功能?
最接近 Python 列表的 Java 是 ArrayList<> 并且可以这样声明
//Declaring an ArrayList
ArrayList<String> stringArrayList = new ArrayList<String>();
//add to the end of the list
stringArrayList.add("foo");
//add to the beggining of the list
stringArrayList.add(0, "food");
//remove an element at a spesific index
stringArrayList.remove(4);
//get the size of the list
stringArrayList.size();
//clear the whole list
stringArrayList.clear();
//copy to a new ArrayList
ArrayList<String> myNewArrayList = new ArrayList<>(oldArrayList);
//to reverse
Collections.reverse(stringArrayList);
//something that could work as "pop" could be
stringArrayList.remove(stringArrayList.size() - 1);
Run Code Online (Sandbox Code Playgroud)
Java 提供了大量集合,您可以在此处查看 Oracle 在其网站上提供的教程https://docs.oracle.com/javase/tutorial/collections/
重要提示:与 Python 不同,在 Java 中,您必须声明列表在实例化时将使用的数据类型。
小智 5
存在几个集合,但您可能正在寻找 ArrayList
在 Python 中,您可以简单地声明一个列表,如下所示:
myList = []
并开始使用它。
在 Java 中,最好先从接口声明:
List<String> myList = new ArrayList<String>();
Python Java
append add
Remove remove
len(listname) list.size
Run Code Online (Sandbox Code Playgroud)
例如,根据您可能需要实现的对象Compactor或Comparable.
ArrayList 将随着您添加项目而增长,无需自行扩展。
至于reverse()and pop(),我会参考你可以参考:
| 归档时间: |
|
| 查看次数: |
9034 次 |
| 最近记录: |