Home

aslist

asList, commonly encountered as Arrays.asList in the Java standard library, is a static generic method in java.util.Arrays. It returns a List<T> that is backed by a given array, providing a convenient way to use the List interface without copying elements.

The list produced by asList has a fixed size equal to the length of the underlying array.

A common pitfall involves primitive arrays. When a primitive array is passed, asList treats it as a

Use cases for asList include adapting a fixed-size array to APIs that require a List without copying

You
can
read
and
write
elements
via
get
and
set,
and
you
can
use
standard
list
operations
such
as
contains
or
indexOf.
However,
you
cannot
add
or
remove
elements
from
this
list;
any
attempt
to
structurally
modify
it
(for
example,
add,
remove,
or
clear)
results
in
an
UnsupportedOperationException.
Because
the
list
is
backed
by
the
original
array,
changes
made
through
the
list
are
reflected
in
the
array,
and
changes
to
the
array
are
reflected
in
the
list.
single
element
of
type
int[]
(or
the
corresponding
primitive
array
type),
producing
a
List<int[]>
with
one
element
rather
than
a
List<Integer>.
To
obtain
a
List<Integer>,
provide
an
array
of
wrapper
types
(e.g.,
new
Integer[]{1,
2,
3})
or
use
a
stream
to
box
values.
data.
It
is
unsuitable
when
a
truly
resizable
list
is
needed.
For
a
resizable
list,
a
common
workaround
is
new
ArrayList<>(Arrays.asList(array)).
For
immutable
needs,
newer
Java
versions
offer
alternatives
like
List.of,
which
does
not
reflect
an
underlying
array.