2015-05-02 20 views
5

In Python, è consentito utilizzare indici di array negativi per contare a partire dal lato destro di un array. Ad esempio, array [-1] è l'ultimo elemento e array [-2] è il penultimo elemento nell'array. Come lo faresti in Java?Come implementare gli indici negativi in ​​java?

+1

Ora è più facile capire cosa viene chiesto. Qualcuno potrebbe riaprire questa domanda per favore? –

+1

Ovviamente puoi creare il tuo oggetto. Ma avrà metodi come PythonArray.getElement (int elementIndex) – borjab

risposta

19

Java non supporta gli indici negativi, per accedere l'ultima cella, è necessario utilizzare

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

indice Java pedice inizia con 0. Non può essere utilizzato indice negativo. Se usato affatto, java lancia l'indice di array fuori limite. Eccezione.

2

di implementare qualcosa di simile, si dovrebbe creare una lista circolare, doppiamente legato ... non ho compilare e testare questo, ma questa è l'idea generale ...

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()); 
} 
Problemi correlati