2013-01-10 16 views
26

Czy jest możliwe dodanie łańcucha do początku tablicy String bez powtarzania całej tablicy.Dodaj ciąg do początku tablicy łańcuchów

+0

Korzystanie inną strukturę danych, który odpowiada Twoim potrzebom (np 'ArrayList') byłoby lepiej. – Sulthan

+1

Użyj ArrayUtils.add (tablica T [], indeks int, element T) (https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils. html # add-T: A-int-T-) –

Odpowiedz

20

Jedynym sposobem, aby to zrobić, to zachować bufor pierścieniowy. np. masz licznik, który pamięta, gdzie jest początek, i przenosisz go zamiast przenosić wszystkie wpisy w tablicy. Działa to tylko dlatego, że ponownie definiujesz, co oznacza "start".

Zobacz źródło dla ArrayDeque który ma trzy pola

86  /** 
    87  * The array in which the elements of the deque are stored. 
    88  * The capacity of the deque is the length of this array, which is 
    89  * always a power of two. The array is never allowed to become 
    90  * full, except transiently within an addX method where it is 
    91  * resized (see doubleCapacity) immediately upon becoming full, 
    92  * thus avoiding head and tail wrapping around to equal each 
    93  * other. We also guarantee that all array cells not holding 
    94  * deque elements are always null. 
    95  */ 
    96  private transient E[] elements; 
    97 
    98  /** 
    99  * The index of the element at the head of the deque (which is the 
    100  * element that would be removed by remove() or pop()); or an 
    101  * arbitrary number equal to tail if the deque is empty. 
    102  */ 
    103  private transient int head; 
    104 
    105  /** 
    106  * The index at which the next element would be added to the tail 
    107  * of the deque (via addLast(E), add(E), or push(E)). 
    108  */ 
    109  private transient int tail; 

więc dodanie do początku działa tak

224  public void addFirst(E e) { 
    225   if (e == null) 
    226    throw new NullPointerException(); 
    227   elements[head = (head - 1) & (elements.length - 1)] = e; 
    228   if (head == tail) 
    229    doubleCapacity(); 
    230  } 


    312  /** 
    313  * @throws NoSuchElementException {@inheritDoc} 
    314  */ 
    315  public E getFirst() { 
    316   E x = elements[head]; 
    317   if (x == null) 
    318    throw new NoSuchElementException(); 
    319   return x; 
    320  } 

Uwaga: przesuwa głowicę zamiast przesuwania wszystkich elementów w dół tablicy .

+0

Jestem ciekawy. Czy możesz to zrobić z nieutrwaloną długością pierścienia? Czy masz przykładowy pseudokod? – Jerome

+0

@Jerome Dodany kod z ArrayDeque, który nie jest naprawiony. Podwaja rozmiar tablicy, gdy jest to wymagane. –

4

Nie możesz ... Musisz przesunąć wszystkie ciągi nadchodzące po nim, aby pomieścić nowy ciąg. Jeśli bezpośrednio dodasz go do 0-tego indeksu, stracisz poprzedni element tam:

1

W tym celu powinieneś użyć List.

A jeśli chcesz korzystać z tablic szczególnie wewnętrzny, pójść na ArrayList

+0

Nie możesz wykonać getFirst (...), getLast (...), addFirst (...), addLast (...), removeFirst (.. .) lub removeLast (...) z ArrayList. Nie zapewnia dodatkowych metod łatwego operowania na końcach listy, ponieważ LinkedList ma –

+2

@Sibi Myślę, że znajdziesz za pomocą add (indeks int, E e) ... zobacz tutaj http://docs.oracle .com/javase/6/docs/api/java/util/List.html # dodaj% 28int,% 20E% 29 – xagyg

+0

@xagyg Zgadzam się – Jerome

9

spróbować

String[] a = {"1", "2"}; 
    String[] a2 = new String[a.length + 1]; 
    a2[0] = "0"; 
    System.arraycopy(a, 0, a2, 1, a.length); 
+13

-1 To oczywiście będzie iterować po wszystkich elementach tablicy. –

3
String[] myArray= {"hi","hi2"}; 
List<String> temp = new ArrayList<String>(Arrays.asList(prova)); 
temp.add(0, "h3"); 
myArray = temp.toArray(new String[temp.size()]); 
+0

W rzeczywistości twoje rozwiązanie nie działa asis. Oto dlaczego: http: // stackoverflow.com/a/2965808/1515058 To zadziała: String [] myArray = {"hi", "hi2"}; Lista lista = nowa lista_połączeń (Arrays.asList (myArray)); list.add (0, "h3"); myArray = list.toArray (new String [temp.size()]); –

1

Najlepszy mogę zarządzać ...

public static void main(String[] args) { 
     String[] s = new String[] { "a", "b", "c" }; 
     System.out.println(Arrays.toString(prepend(s,"d"))); 
} 

public static String[] prepend(String[] a, String el) { 
     String[] c = new String[a.length+1]; 
     c[0] = el; 
     System.arraycopy(a, 0, c, 1, a.length); 
     return c; 
} 
+0

@EvgeniyDorofeev Dobra odpowiedź. Pokonaj mnie. – xagyg

1

można zrobić kilka rzeczy jak poniżej

public class Test { 

public static String[] addFirst(String s[], String e) { 
    String[] temp = new String[s.length + 1]; 
    temp[0] = e; 
    System.arraycopy(s, 0, temp, 1, s.length); 
    return temp; 
} 

public static void main(String[] args) { 
    String[] s = { "b", "c" }; 
    s = addFirst(s, "a"); 
    System.out.println(Arrays.toString(s)); 
} 
} 
4

ta jest skorygowana wersja rozwiązania proponowane autor: @matteosilv:

String[] myArray= {"hi","hi2"}; 
List<String> list = new LinkedList<String>(Arrays.asList(myArray)); 
list.add(0, "h3"); 
myArray = list.toArray(new String[list.size()]); 
6

Jeśli używasz już Guava można użyć ObjectArrays::concat to zrobić:

String[] args = ...; 
ObjectArrays.concat("prepended", args); 
Powiązane problemy