2017-09-21 1 views
0

ArrayList에 대한 UnorderedList의 메소드가 어떻게 생겼는지 궁금합니다. addToFront, addToRear 및 addAfter (모두 T 요소 포함)가 있지만, 배열로 구현 된 것을 본 적이 있습니다 (아래 참조). 대신 ArrayList를 사용할 수 있습니까? 이것이 어떻게 방법을 바꿀까요? 내 질문이 이해되기를 바랍니다.Java - ArrayList의 순서없는리스트 메소드?

public void addToFront(T element) { 

    if (size() == list.length) { 
     expandCapacity(); 
    } 

    for (int i = this.size(); i > 0; i--) { 
     this.list[i] = this.list[i-1]; 
    } 

    this.list[0] = element; 
    this.rear++; 
} 

/** 
* Adds the specified element to the rear of this list. 
* 
* @param element the element to be added to the list 
*/ 
public void addToRear(T element) { 
    if (size() == list.length) { 
     expandCapacity(); 
    } 

    this.list[rear] = element; 
    this.rear++; 
} 

/** 
* Adds the specified element after the specified target element. 
* Throws an ElementNotFoundException if the target is not found. 
* 
* @param element the element to be added after the target element 
* @param target the target that the element is to be added after 
*/ 
public void addAfter(T element, T target) { 
    if (size() == list.length) { 
     expandCapacity(); 
    } 

    int scan = 0; 
    while (scan < rear && !target.equals(list[scan])) { 
     scan++; 
    } 

    if (scan == rear) { 
     throw new ElementNotFoundException("list"); 
    } 

    scan++; 
    for (int scan2 = rear; scan2 > scan; scan2--) { 
     list[scan2] = list[scan2 - 1]; 
    } 

    list[scan] = element; 
    rear++; 
} 
} 
+1

별로입니다. 한번 시도해보십시오. 코드에 사용 된 일부 기본 제공 표현이 변경 될 수 있습니다. – nullpointer

+0

@nullpointer 용량 확장에 관해서는 ArrayList에 필요합니까? 내 지식은 제한 될 수 있지만 용량이 자동으로 커지지는 않습니까? –

답변

1

의 ArrayList는 과도 배열의 크기 관리 측면을 추상화 :

내가 건너 한 코드입니다. 체크 아웃 :

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(int,%20E)

import java.util.ArrayList; 

public class Test<T> { 
    ArrayList<T> yourArray; 

    Test() { 
    // Initialize to avoid NPEs 
    yourArray = new ArrayList<T>(); 
    } 

    public void addToFront(T element) { 
    yourArray.add(0, element); 
    } 

    public void addToRear(T element) { 
    yourArray.add(yourArray.size(), element); 
    } 

    public void addAfter(T element, T target) { 
    yourArray.add(yourArray.indexOf(target) + 1, element); 
    } 

    public void addBefore(T element, T target) { 
    final int location = yourArray.indexOf(target); 

    if (location == 0) { 
     addToFront(element); 
    } else { 
     yourArray.add(yourArray.indexOf(target) - 1, element); 
    } 
    } 
} 
+0

네 말이 맞아. 내 ArrayList 메서드를 닦아야한다고 생각합니다. 첫 번째 인덱스에 요소를 추가하기 만하면 내용을 오른쪽으로 이동할 수 있다는 사실을 잊어 버렸습니다. –

관련 문제