2013-04-08 21 views
0

我正在寫一個程序在整個地圖上執行一個星形搜索。我創建了一個保存地圖所有節點的類。在java中改變一個類的數組的值

public Node { 
    Node up_node, right_node, down_node, left_node; 
} 

public class Star { 
    public static void main(String args[]) { 
     Node a=new Node(); 
     Node b=new Node(); 
     Node h=new Node(); 
     Node here=new Node(); 

     Node[] NextNode; 
     NextNode = new Node[10]; 
     for(int i=0;i<10;i++) { 
      NextNode[i]=new Node(); 
     } 
     int j=0; 
     a.up_node=h; 
     a.right_node=b; 

     b.left_node=a; 

     h.down_node=a; 

     //if certain conditions are met 
     NextNode[j].here_node=a.up_node; 
     //what i was hoping to do is copy the node a.up which is h 
    } 
} 

在這種情況下進入NextNode [0]。但是它會一直返回某種內存地址:[email protected]:test是包的名稱,請幫助!

+1

返回哪裏?如果您嘗試使用system.out.println節點對象,那麼除非您覆蓋類節點的toString方法,否則您將最終得到Node @ XXXX。 – 2013-04-08 19:29:00

+0

除了其他Node的引用之外每個節點中將包含什麼'value'?如果你有'value',那麼在'toString()'方法中返回'value'的'String'格式。這將解決您的問題 – 2013-04-08 19:29:14

+1

「它一直迴歸」非常模糊。目前還不清楚你在哪裏看到的,但幾乎肯定是在'Node'上調用'toString()'的結果 - 並且你沒有重寫該方法... – 2013-04-08 19:29:14

回答

1

@override toString()方法顯示你的類的內部屬性。

默認情況下,java顯示完整的類名@ hashCode的值。

0

我們知道我們寫的每個班級都是Object班的孩子。當我們打印一個Object的孩子時,它會打印它的toString()方法。默認情況下它是內存位置的哈希值。所以它打印排序奇怪的事情。如果我們@overridingtoString方法返回更有意義的東西給我們,那麼我們可以解決這個問題。如果我們可以指定我們的節點類別,我認爲我們可以很容易地跟蹤它們

class Node(){ 
     String nameOfNode;  
     //contractor to keep track of where it goes. 
     public Node(String a){ 
      nameOfNode=a; 

     } 
     //when we will print a Node it is going to print its name 
     public String toString(){ 
       return nameOfNode; 
     } 
} 

然後它會打印節點的名稱。它會停止顯示奇怪的內存地址。

並更換new Node()具有鮮明的名字new Node("a name")

1

變量在Java中的對象引用沒有實際對象NextNode[j].here_node = a.up_node;將使NextNode[j].here_nodea.up_node指向相同的對象。這不是你想要的嗎?

如果你想使對象的一個​​全新的副本,那麼你就可以實現在Node類:

public class Node { 
    Node up_node, right_node, down_node, left_node; 

    public Node clone() { 
    Node ret = new Node(); 

    // copy the properties 
    ret.up_node = this.up_node; 
    ... 

    return ret; 
    } 
} 

現在

NextNode[j].here_node = a.up_node.clone(); 

做一個拷貝(雖然這只是一個淺的 - 副本將通過其字段指向相同的對象,而不是它們的副本)。

我假設你對代碼返回「一個地址」的混淆是因爲你試圖打印一個節點,例如,

System.out.println(a.up_node); 

你會得到類似[email protected],但儘量

System.out.println(NextNode[j].here_node); 

,你應該得到完全相同的字符串,這表明他們指向同一個對象。

爲了得到更好的東西,你必須重寫Node的執行toString()。下面是一個例子,將給每個Node一個唯一的編號:

public class Node { 
    Node up_node, right_node, down_node, left_node; 

    // how many nodes were created 
    private static int count = 0; 

    // the number of this node 
    private int number; 

    public Node() { 
    // increment the number of nodes created 
    ++Node.count; 
    // assign that number to this node 
    this.number = Node.count; 
    } 

    public String toString() { 
    return "Node #" + this.number; 
    } 
} 
相關問題