Using Java List When Array is Enough

Is it advisable to use a list of Java collections in cases where you know the size of the list before hand, and you can also use an array there? Are there any performance flaws?

Is it possible to initialize a list using elements in a single expression, such as an array (a list of all elements separated by commas)?

+3
source share
7 answers

Is it advisable to use a list of Java collections in cases where you know the size of the list before hand, and you can also use an array there?

In some (perhaps most) circumstances, yes, of course, it is advisable to use collections in any case, in some cases it is impractical.

On the pro side:

  • , , contains, insert, remove ..
  • , .
  • , ..., .

con:

  • , , .
  • , .

, .

/ . ( , char[], . , , , , !)

+4

/ . .

:

Arrays.asList(yourArray);

:

, . ( "write through" .) API Collection.toArray. RandomAccess.

, , .

+4

Java , , ?

, . . . , ...

  • - , Collection
  • - List -, .contains, .lastIndexOf, ,
  • Collections, reverse...

Collection/List.

, array = { , }?

List<String> list = Arrays.asList("foo", "bar");

List<String> arrayList = new ArrayList<String>(Arrays.asList("foo", "bar"));

List<String> list = new ArrayList<String>() {{ add("foo"); add("bar"); }};
+2

1) a Collection . , java.util.Set, java.util.List, , java.util.SortedSet

2) Array, Arrays.asList()

List<String> myStrings = Arrays.asList(new String[]{"one", "two", "three"});

, :

List<String> myStrings = new ArrayList<String>(){
// this is the inside of an anonymouse class
{
    // this is the inside of an instance block in the anonymous class
    this.add("one");
    this.add("two");
    this.add("three");
}};
+2

, .

(, ArrayList) , " " , "" .

+2

, : ? ? , :

  • : A B → A [] B [], ArrayStoreExceptions
  • ...

. 25 " " Java-.

, , . ......

, array = { , }?

Arrays.asList(): http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29

+2

Java? , ? ?

, .

, array = { }?

. Arrays.asList().

+1

Source: https://habr.com/ru/post/1792193/


All Articles