Utility method for wrapping an object in a collection

前端 未结 5 671
抹茶落季
抹茶落季 2021-02-06 22:44

I\'m looking for a static method in the Java core libraries or some other commonly used dependency — preferably one of Apache — that does the following:

public s         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 23:12

    Here are some efficient ways to wrap Java object(s) in List, as of Java 8.

    Collections.singletonList: Single item, immutable, since 1.3.
    Collections.singletonList( object )
    High performance backed by internal class.

    Collections.nCopies: One object, zero to many items, immutable, since 1.2.
    Collections.nCopies( number_of_copy, object )
    High performance backed by internal class. All items point to same object.

    Array.asList: Any number of objects, size immutable (individual elements mutable), since 1.2.
    Arrays.asList( object1, object2, object3 )
    Backed by internal class. Items are converted to array at compile time and this array directly backs the List.

    new ArrayList(Collection): Any number of objects, mutable, since 1.2
    new ArrayList<>( Arrays.asList( object1, object2, object3 ) )
    The ArrayList is created with an array clone and an array copy, and so does not use any loops.

提交回复
热议问题