[英]Is there an equivalent to Python's List Comprehension in Java
[英]Java equivalent of Python List
在 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);
Java 提供了大量集合,您可以在此处查看 Oracle 在其网站上提供的教程https://docs.oracle.com/javase/tutorial/collections/
重要提示:与 Python 不同,在 Java 中,您必须声明列表在实例化时将使用的数据类型。
存在多个集合,但您可能正在寻找ArrayList
在 Python 中,您可以简单地声明一个列表,如下所示:
myList = []
并开始使用它。
在 Java 中,最好先从接口声明:
List<String> myList = new ArrayList<String>();
Python Java
append add
Remove remove
len(listname) list.size
例如,根据您可能需要实现Compactor
或Comparable
的对象,对 List 进行排序可能需要更多的工作。
ArrayList
会随着您添加项目而增长,无需自行扩展。
至于reverse()
和pop()
,我会参考你可以参考:
Java有一个叫做list的接口,里面有ArrayList、AbstractList、AttributeList等实现。
https://docs.oracle.com/javase/8/docs/api/java/util/List.html
但是,每个都有不同的功能,我不知道它们是否具有您指定的所有内容,例如 .reverse()。
看看java中的集合。 有很多列表(ArrayList、LinkedList 等)。 选择满足要求和复杂性(空间和时间)所需的最佳数据结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.