![](/img/trans.png)
[英]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.