📜  Java列表

📅  最后修改于: 2020-10-12 09:42:12             🧑  作者: Mango

Java列表

Java中的List提供了维护有序集合的工具。它包含用于插入,更新,删除和搜索元素的基于索引的方法。它也可以有重复的元素。我们还可以将null元素存储在列表中。

List接口可在java.util包中找到,并继承Collection接口。它是ListIterator接口的工厂。通过ListIterator,我们可以向前和向后迭代列表。 List接口的实现类是ArrayList,LinkedList,Stack和Vector。 ArrayList和LinkedList在Java编程中被广泛使用。从Java 5开始不推荐使用Vector类。

列表接口声明

public interface List extends Collection

Java列表方法

Method Description
void add(int index, E element) It is used to insert the specified element at the specified position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection c) It is used to append all of the elements in the specified collection to the end of a list.
boolean addAll(int index, Collection c) It is used to append all the elements in the specified collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
boolean equals(Object o) It is used to compare the specified object with the elements of a list.
int hashcode() It is used to return the hash code value for a list.
E get(int index) It is used to fetch the element from the particular position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list in the correct order.
T[]toArray(T[] a) It is used to return an array containing all of the elements in this list in the correct order.
boolean contains(Object o) It returns true if the list contains the specified element
boolean containsAll(Collection c) It returns true if the list contains all the specified element
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
boolean removeAll(Collection c) It is used to remove all the elements from the list.
void replaceAll(UnaryOperator operator) It is used to replace all the elements from the list with the specified element.
void retainAll(Collection c) It is used to retain all the elements in the list that are present in the specified collection.
Eset(int index, E element) It is used to replace the specified element in the list, present at the specified position.
void sort(Comparator c) It is used to sort the elements of the list on the basis of specified comparator.
Spliterator spliterator() It is used to create spliterator over the elements in a list.
ListsubList(int fromIndex, int toIndex) It is used to fetch all the elements lies within the given range.
int size() It is used to return the number of elements present in the list.

Java列表与ArrayList

List是一个接口,而ArrayList是List的实现类。

如何建立清单

ArrayList和LinkedList类提供List接口的实现。让我们看一下创建列表的示例:

//Creating a List of type String using ArrayList
List list=new ArrayList();

//Creating a List of type Integer using ArrayList
List list=new ArrayList();

//Creating a List of type Book using ArrayList
List list=new ArrayList();

//Creating a List of type String using LinkedList
List list=new LinkedList();

简而言之,您可以创建任何类型的列表。 ArrayList和LinkedList类用于指定类型。在此,T表示类型。

Java列表示例

让我们看一下List的一个简单示例,其中我们使用ArrayList类作为实现。

import java.util.*;
public class ListExample1{
public static void main(String args[]){
 //Creating a List
 List list=new ArrayList();
 //Adding elements in the List
 list.add("Mango");
 list.add("Apple");
 list.add("Banana");
 list.add("Grapes");
 //Iterating the List element using for-each loop
 for(String fruit:list)
  System.out.println(fruit);

}
}

输出:

Mango
Apple
Banana
Grapes

如何将数组转换为列表

我们可以通过遍历数组并使用list.add()方法将数组中的元素一一添加到列表中,从而将Array转换为List。让我们看一个将数组元素转换为List的简单示例。

import java.util.*;
public class ArrayToListExample{
public static void main(String args[]){
//Creating Array
String[] array={"Java","Python","PHP","C++"};
System.out.println("Printing Array: "+Arrays.toString(array));
//Converting Array to List
List list=new ArrayList();
for(String lang:array){
list.add(lang);
}
System.out.println("Printing List: "+list);

}
}

输出:

Printing Array: [Java, Python, PHP, C++]
Printing List: [Java, Python, PHP, C++]

如何将列表转换为数组

我们可以通过调用list.toArray()方法将List转换为Array。让我们看一个将列表元素转换为数组的简单示例。

import java.util.*;
public class ListToArrayExample{
public static void main(String args[]){
 List fruitList = new ArrayList<>();  
 fruitList.add("Mango");  
 fruitList.add("Banana");  
 fruitList.add("Apple");  
 fruitList.add("Strawberry");  
 //Converting ArrayList to Array
 String[] array = fruitList.toArray(new String[fruitList.size()]);  
 System.out.println("Printing Array: "+Arrays.toString(array));
 System.out.println("Printing List: "+fruitList);
}
}

输出:

Printing Array: [Mango, Banana, Apple, Strawberry]
Printing List: [Mango, Banana, Apple, Strawberry]

在列表中获取和设置元素

get()方法返回给定索引处的元素,而set()方法更改或替换该元素。

import java.util.*;
public class ListExample2{
 public static void main(String args[]){
 //Creating a List
 List list=new ArrayList();
 //Adding elements in the List
 list.add("Mango");
 list.add("Apple");
 list.add("Banana");
 list.add("Grapes");
 //accessing the element  
 System.out.println("Returning element: "+list.get(1));//it will return the 2nd element, because index starts from 0
 //changing the element
 list.set(1,"Dates");
 //Iterating the List element using for-each loop
 for(String fruit:list)
  System.out.println(fruit);

 }
}

输出:

Returning element: Apple
Mango
Dates
Banana
Grapes

如何排序清单

有多种方法可以对列表进行排序,这里我们将使用Collections.sort()方法对列表元素进行排序。 java.util包提供了一个实用程序类Collections,它具有静态方法sort()。使用Collections.sort()方法,我们可以轻松地对任何List进行排序。

import java.util.*;
class SortArrayList{
 public static void main(String args[]){
  //Creating a list of fruits
  List list1=new ArrayList();
  list1.add("Mango");
  list1.add("Apple");
  list1.add("Banana");
  list1.add("Grapes");
  //Sorting the list
  Collections.sort(list1);
   //Traversing list through the for-each loop
  for(String fruit:list1)
    System.out.println(fruit);
    
 System.out.println("Sorting numbers...");
  //Creating a list of numbers
  List list2=new ArrayList();
  list2.add(21);
  list2.add(11);
  list2.add(51);
  list2.add(1);
  //Sorting the list
  Collections.sort(list2);
   //Traversing list through the for-each loop
  for(Integer number:list2)
    System.out.println(number);
 }
 
}

输出:

Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51

Java ListIterator接口

ListIterator接口用于沿前后方向遍历元素。

ListIterator接口声明

public interface ListIterator extends Iterator

Java ListIterator接口的方法:

Method Description
void add(E e) This method inserts the specified element into the list.
boolean hasNext() This method returns true if the list iterator has more elements while traversing the list in the forward direction.
E next() This method returns the next element in the list and advances the cursor position.
int nextIndex() This method returns the index of the element that would be returned by a subsequent call to next()
boolean hasPrevious() This method returns true if this list iterator has more elements while traversing the list in the reverse direction.
E previous() This method returns the previous element in the list and moves the cursor position backward.
E previousIndex() This method returns the index of the element that would be returned by a subsequent call to previous().
void remove() This method removes the last element from the list that was returned by next() or previous() methods
void set(E e) This method replaces the last element returned by next() or previous() methods with the specified element.

ListIterator接口示例

import java.util.*;
public class ListIteratorExample1{
public static void main(String args[]){
List al=new ArrayList();  
al.add("Amit");  
al.add("Vijay");  
al.add("Kumar");  
al.add(1,"Sachin");  
ListIterator itr=al.listIterator();  
System.out.println("Traversing elements in forward direction");  
while(itr.hasNext()){  

System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());  
}  
System.out.println("Traversing elements in backward direction");  
while(itr.hasPrevious()){  

System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());  
}  
}
}

输出:

Traversing elements in forward direction
index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
Traversing elements in backward direction
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit

清单范例:书籍

让我们看一个添加书的清单的例子。

import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ListExample5 {
public static void main(String[] args) {
//Creating list of Books
List list=new ArrayList();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}

输出:

101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications and Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6