Java 不可变的列表

Java 不可变的列表

  • ImmutableList,顾名思义,是一种不可变的List类型。它意味着List的内容在声明后是固定的或不变的,也就是说,它们是 只读的
  • 如果试图在List中添加、删除和更新元素,就会抛出 UnsupportedOperationException
  • 一个ImmutableList也不允许出现空元素。
  • 如果试图用空元素创建ImmutableList,会抛出 NullPointerException 。如果试图在List中添加空元素,则会抛出 UnsupportedOperationException

ImmutableList的优点

  • 它们是 线程安全的
  • 它们具有 内存效率
  • 由于它们是不可变的,因此它们可以毫无问题地 传递给第三方库

请注意 ,它是一个不可变的集合,而不是不可变对象的集合,所以它里面的对象可以被修改。

类的声明

@GwtCompatible(serializable=true,
               emulated=true)
public abstract class ImmutableList
extends ImmutableCollection
implements List, RandomAccess

类的层次结构

java.lang.Object
  ↳ java.util.AbstractCollection
      ↳ com.google.common.collect.ImmutableCollection
          ↳ com.google.common.collect.ImmutableList 

创建ImmutableList
ImmutableList可以通过各种方法创建。这些方法包括

  1. 使用Guava的copyOf()函数从现有列表中获取
// Below is the Java program to create ImmutableList
  
import com.google.common.collect.ImmutableList;
import java.util.*;
  
class GFG {
  
    // Function to create ImmutableList from List
    public static <T> void iList(List<T> list)
    {
        // Create ImmutableMap from Map using copyOf()
        ImmutableList<T> immutableList =
                          ImmutableList.copyOf(list);
  
        // Print the ImmutableMap
        System.out.println(immutableList);
    }
  
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>(
            Arrays.asList("Geeks", "For", "Geeks"));
  
        iList(list);
    }
}

输出:

[Geeks, For, Geeks]
  1. 使用Guava的of()函数创建ImmutableList
// Below is the Java program to create ImmutableList
  
import com.google.common.collect.ImmutableList;
import java.util.*;
  
class GFG {
  
    // Function to create ImmutableList
    public static void iList()
    {
        // Create ImmutableList using of()
        ImmutableList<String> immutableList = 
               ImmutableList.of("Geeks", "For", "Geeks");
  
        // Print the ImmutableMap
        System.out.println(immutableList);
    }
  
    public static void main(String[] args)
    {
        iList();
    }
}

输出:

[Geeks, For, Geeks]
  1. 使用Java 9工厂的Of()方法

在Java中,与Set、Map或List一起使用of()来创建一个Immutable List。

请注意:下面的程序是Java 9的,因此你需要一个Java 9的编译器来运行它们

// Java code illustrating of() method to
// create a ImmutableSet
import java.util.*;
import com.google.common.collect.ImmutableList;
  
class GfG {
    public static void main(String args[])
    {
        // non-empty immutable set
        List<String> list = List.of("Geeks", "For", "Geeks");
  
        // Let's print the list
        System.out.println(list);
    }
}

输出:

[Geeks, For, Geeks]
  1. 使用ImmutableList的Builder()

在Guava中,ImmnutableList类提供了一个函数Builder()。通过这个函数,一个新的ImmutableList可以被创建,或者
一个ImmutableList可以从一个现有的List中创建,或者两者都可以。

* **创建一个新的ImmutableList**
// Java code illustrating of() method to
// create a ImmutableList
import java.util.*;
import com.google.common.collect.ImmutableList;
  
class GfG {
    public static void main(String args[])
    {
        // non-empty immutable set
        ImmutableList<String> iList = ImmutableList.<String>builder()
                                          .add("Geeks", "For", "Geeks")
                                          .build();
  
        // Let's print the List
        System.out.println(iList);
    }
}

输出:

[Geeks, For, Geeks]
  • 从现有的List创建一个ImmutableList
// Java code illustrating of() method to
// create a ImmutableList
import java.util.*;
import com.google.common.collect.ImmutableList;
  
class GfG {
    public static void main(String args[])
    {
        // non-empty immutable set
        List<String> list = List.of("Geeks", "For", "Geeks");
        ImmutableList<String> iList = ImmutableList.<String>builder()
                                          .addAll(list)
                                          .build();
  
        // Let's print the List
        System.out.println(iList);
    }
}

输出:

[Geeks, For, Geeks]
  • 创建一个新的ImmutableList,包括现有的List
// Java code illustrating of() method to
// create a ImmutableList
import java.util.*;
import com.google.common.collect.ImmutableList;
  
class GfG {
    public static void main(String args[])
    {
        // non-empty immutable set
        List<String> list = List.of("Geeks", "For", "Geeks");
        ImmutableList<String> iList = ImmutableList.<String>builder()
                                          .addAll(list)
                                          .add("Computer", "Portal", )
                                          .build();
  
        // Let's print the set
        System.out.println(iList);
    }
}

输出:

[Geeks, For, Geeks, Computer, Portal]

尝试改变ImmutableList

如前所述,下面的程序将抛出 UnsupportedOperationException

// Java code to show that UnsupportedOperationException
// will be thrown when ImmutableList is modified.
import java.util.*;
  
class GfG {
    public static void main(String args[])
    {
        // empty immutable map
        List<String> list = List.of();
  
        // Lets try adding element in  List
        List.add("Geeks");
    }
}

输出:

Exception in thread "main" java.lang.UnsupportedOperationException
    at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:218)
    at ImmutableListDemo.main(Main.java:16)

它与Collections.unmodifiableList()有什么不同?

Collections.unmodifiableList在现有的List周围创建一个包装器,这样包装器就不能被用来修改它。但是我们仍然可以改变原来的List。

// Java program to demonstrate that a List created using
// Collections.unmodifiableList() can be modified indirectly.
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("Geeks");
  
        // Create ImmutableList from List using copyOf()
        List<String> iList = Collections.unmodifiableList(list);
  
        // We change List and the changes reflect in iList.
        list.add("For");
        list.add("Geeks");
  
        System.out.println(iList);
    }
}

输出:

[Geeks, For, Geeks]

如果我们从一个现有的List创建一个ImmutableList,并改变现有的List,ImmutableList不会改变,因为已经创建了一个副本。

// Below is a Java program for
// Creating an immutable List using copyOf()
// and modifying original List.
import java.io.*;
import java.util.*;
import com.google.common.collect.ImmutableList;
  
class GFG {
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("Geeks");
  
        // Create ImmutableList from List using copyOf()
        ImmutableList<String> iList = ImmutableList.copyOf(list);
  
        // We change List and the changes wont reflect in iList.
        list.add("For");
        list.add("Geeks");
  
        System.out.println(iList);
    }
}

输出:

[Geeks]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程