2015-05-02 15 views
5

W języku Python dozwolone jest używanie ujemnych indeksów tablicowych do liczenia począwszy od prawej strony tablicy. Na przykład tablica [-1] jest ostatnim elementem, a tablica [-2] jest drugim ostatnim elementem w tablicy. Jak zrobiłbyś to w Javie?Jak zaimplementować indeksy wykluczające w języku Java?

+1

Teraz łatwiej jest zrozumieć, o co się pyta. Czy ktoś mógłby ponownie otworzyć to pytanie? –

+1

Oczywiście możesz stworzyć swój własny obiekt. Ale będzie miał metody takie jak PythonArray.getElement (int elementIndex) – borjab

Odpowiedz

19

Java nie obsługuje ujemnych indeksów, aby przejść do ostatniej komórki, należy użyć

array[array.length-1] = lastElement; 
3

Indeks Java indeks zaczyna się od 0. Nie wskaźnik ujemny może być używany. Jeśli w ogóle używany, to java wyrzuci indeks macierzy poza granice wyjątku.

2

zaimplementować coś takiego, trzeba by stworzyć okrągły, podwójnie połączonej listy ... nie skompilować i przetestować, ale jest to ogólna idea ...

public class LinkedList { 
    Integer node; 
    LinkedList next; 
    LinkedList prev; 
    public LinkList(Integer node) { 
     this.node = node; 
     this.next = this; 
     this.prev = this; 
    } 
    public void insert(Integer node) { 
     if(this.node == null) { 
      this.node = node; 
      this.next = this; 
      this.prev = this; 
     } 
     else if(this.next == null) { 
      this.next = new LinkedList(node); 
      this.prev = node 
      this.next.prev = this; 
      this.next.next = this; 
     } 
     else { 
      this.next(node, this); 
     } 
    } 
    private void insert(Integer node, LinkedList head) { 
     if(this.next == null) { 
      this.next = new LinkedList(node); 
      this.next.prev = this; 
      this.next.next = head; 
     } 
     else { 
      this.next(node, head); 
     } 
    } 
    public Interger get(int index) { 
     int cursor = 0; 
     if(index == cursor) { 
      return this.node; 
     } 
     else if(index < cursor) { 
      return this.prev.get(index, cursor-1); 
     } 
     else { 
      return this.next.get(index, cursor+1); 
     } 
    } 
    private Interger get(int index, int cursor) { 
     if(index == cursor) { 
      return this.node; 
     } 
     else if(index < cursor) { 
      return this.prev.get(index, cursor-1); 
     } 
     else { 
      return this.next.get(index, cursor+1); 
     } 
    } 
} 
public static void main(String[] args) { 
    LinkedList list = new LinkedList(new Integer(1)); 
    list.insert(new Integer(2)); 
    list.insert(new Integer(3)); 
    System.out.println(list.get(-1).toString()); 
} 
Powiązane problemy