Development Tip

Java의 ArrayList 또는 List 선언

yourdevel 2020. 12. 1. 19:51
반응형

Java의 ArrayList 또는 List 선언


이 두 선언의 차이점은 무엇입니까?

선언 1 :

ArrayList<String> arrayList = new ArrayList<String>();

선언 2 :

List<String> arrayList = new ArrayList<String>();

List<String> arrayList = new ArrayList<String>();

클라이언트로 반환하는 동안 구현 세부 정보를 숨기려는 경우 일반적이며 나중에 구현 ArrayListLinkedList투명하게 변경할 수 있습니다 .

이 메커니즘은 클라이언트 측에서 최소한의 변경으로 특정 시점에 구현 세부 사항을 변경할 수있는 라이브러리 등을 디자인하는 경우에 유용합니다.

ArrayList<String> arrayList = new ArrayList<String>();

이 명령은 항상 반환해야합니다 ArrayList. 시간의 어떤 시점에서 당신은에 구현 세부 사항을 변경하려는 경우 LinkedList에도 사용하는 클라이언트 측에서,이 있어야 변화 LinkedList대신 ArrayList.


List인터페이스이며 ArrayListList 인터페이스의 구현입니다. ArrayList클래스에는 (i.e clone(), trimToSize(), removeRange() and ensureCapacity())List 인터페이스에서 사용할 수있는 메서드 외에 몇 가지 메서드 만 있습니다. 이것에는 큰 차이가 없습니다.

   1. List<String> l = new ArrayList<>();
   2. ArrayList<String> l = new ArrayList<>();

첫 번째를 사용하면 List 인터페이스에서 사용할 수있는 메서드를 호출 할 수 있으며 ArrayList클래스 에서 사용할 수있는 새 메서드를 호출 할 수 없습니다 . ArrayList두 번째 방법을 사용하는 경우 에서 사용 가능한 모든 방법을 자유롭게 사용할 수 있습니다 .

자바 애플리케이션을 개발할 때 컬렉션 프레임 워크 개체를 메서드에 대한 인수로 전달해야 할 때 첫 번째 접근 방식을 사용하는 것이 더 낫기 때문에 첫 번째 접근 방식이 더 좋습니다.

List<String> l = new ArrayList<>();
doSomething(l);

향후 성능 제약으로 인해 구현을 변경 LinkedList하거나 List인터페이스 를 구현하는 다른 클래스 를 사용하는 경우 ArrayList한 지점 (인스턴스화 부분)에서만 변경해야합니다.

List<String> l = new LinkedList<>();

그렇지 않으면 특정 클래스 구현을 메서드 인수로 사용한 모든 위치에서 변경해야합니다.


차이점은 변형 1을 사용하면 ArrayList변형 2 를 사용하면 List<String>.

나중에 List<String> arrayList = new LinkedList<String>();번거롭지 않게 변경할 수 있습니다 . 변형 1은 해당 줄뿐만 아니라 다른 부분도 ArrayList<String>.

따라서 내가 사용하는 거라고 List<String>내가 추가 메서드 호출 할 필요 했어 경우를 제외하고, 거의 모든 경우에 ArrayList(지금까지의 경우 적이없는) 제공합니다 : ensureCapacity(int)trimToSize().


첫 번째 선언은 ArrayList 여야하고 두 번째 선언은 다른 List 유형으로 쉽게 변경할 수 있습니다. 따라서 두 번째는 특정 구현이 필요하지 않다는 것을 분명히하기 때문에 선호됩니다. (때로는 실제로 하나의 구현이 필요하지만 드문 경우입니다)


기본적으로 Java class MyStructure<T extends TT>의 주요 기능 중 하나 인 일반 유형 선언 (예 :)을 통해 하나의 구조 구현에 여러 유형의 객체를 저장할 수 있습니다 .

객체 지향 접근 방식은 모든 종류의 객체와 함께 구조를 사용할 수있는 기능 (몇 가지 규칙을 준수하는 한)의 분리를 통해 모듈 성과 재사용 성을 기반으로합니다.

다음과 같이 인스턴스화 할 수 있습니다.

ArrayList list = new ArrayList();

대신에

ArrayList<String> list = new ArrayList<>();

제네릭 유형을 선언하고 사용함으로써 관리 할 객체 종류의 구조를 알리고 컴파일러는 해당 구조에 잘못된 유형을 삽입하는 경우 등을 알릴 수 있습니다. 의 말을하자:

// this works
List list1 = new ArrayList();
list1.add(1);
list1.add("one");

// does not work
List<String> list2 = new ArrayList<>();
list2.add(1); // compiler error here
list2.add("one");

몇 가지 예를 보려면 문서 문서를 확인하십시오 .

/**
 * Generic version of the Box class.
 * @param <T> the type of the value being boxed
 */
public class Box<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

그런 다음 다음과 같은 것을 인스턴스화 할 수 있습니다.

class Paper  { ... }
class Tissue { ... }

// ...
Box<Paper> boxOfPaper = new Box<>();
boxOfPaper.set(new Paper(...));

Box<Tissue> boxOfTissues = new Box<>();
boxOfTissues.set(new Tissue(...));

여기서 가장 중요한 것은 상자에 넣을 개체 유형을 지정하는 것입니다.

사용에 관해서 Object l = new ArrayList<>();List또는 ArrayList구현에 액세스 하지 않으므로 컬렉션으로 많은 작업을 수행 할 수 없습니다.


구현을 다음과 같이 쉽게 변경할 List수 있습니다 Set.

Collection<String> stringList = new ArrayList<String>();
//Client side
stringList = new LinkedList<String>();

stringList = new HashSet<String>();
//stringList = new HashSet<>(); java 1.7 and 1.8

There are a few situations where you might prefer the first one to (slightly) improve performance, for example on some JVMs without a JIT compiler.

Out of that kind of very specific context, you should use the first one.


Possibly you can refer to this link http://docs.oracle.com/javase/6/docs/api/java/util/List.html

List is an interface.ArrayList,LinkedList etc are classes which implement list.Whenyou are using List Interface,you have to itearte elements using ListIterator and can move forward and backward,in the List where as in ArrayList Iterate using Iterator and its elements can be accessed unidirectional way.


List is interface and ArrayList is implemented concrete class. It is always recommended to use.

List<String> arrayList = new ArrayList<String>();

Because here list reference is flexible. It can also hold LinkedList or Vector object.


Whenever you have seen coding from open source community like Guava and from Google Developer (Android Library) they used this approach

List<String> strings = new ArrayList<String>();

because it's hide the implementation detail from user. You precisely

List<String> strings = new ArrayList<String>(); 

it's generic approach and this specialized approach

ArrayList<String> strings = new ArrayList<String>();

For Reference: Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces

참고URL : https://stackoverflow.com/questions/12321177/arraylist-or-list-declaration-in-java

반응형