0


挿入が文字タイプのオブジェクトであるかどうかを検出するツリーを作成し、それぞれを比較して[右または左]を挿入する場所を決定します(ASCIIテーブルの位置で検出できることを知っています)。は int のオブジェクトで、同じ操作を行います。
私の質問:
1. ツリーを作成し、同時にコンパターを設定する必要があります (たとえば、Chars のツリーの場合、Chars をチェックする Chars_comperator になり、彼は (Java の) Comparator を実装します)。コードは現在、int のみに適しています。オブジェクトを文字列に変換してから int に変換し、このすべてを比較して、挿入する場所を決定するため、これを行う必要がある方法ですか? または、それを行う別の方法がありますすべての種類のオブジェクトを処理できますか? ここに私のコードとツリーの作成方法を示します。

ツリークラス

public class tree {

bNode root;
public tree() {
    this.root = null;
}
public boolean isEmpty(){
    return root==null;
}
public void insert(Object data)
{
    if(isEmpty())
        this.root = new bNode(data);
    else
        this.root.insert(data);

   }
 }


bNode クラス

public class bNode {
 protected Object data;
 protected bNode left;
 protected bNode right;


public bNode(Object data) {
    this.data = data;
    this.left = null;
    this.right = null;
}

public void insert(Object data){

    if(Integer.parseInt(data.toString())<Integer.parseInt(this.data.toString())){
        if(this.left==null)
             this.left = new bNode(data);
        else 
            this.left.insert(data);

    }
    else{
        if(this.right==null)
             this.right = new bNode(data);
        else 
            this.right.insert(data);



    }
}

メインクラス

public class Main {

/**
 * @param args
 */
public static void main(String[] args) {
    tree x = new tree();
    char a = 'G';
    x.insert(a);
    x.insert(60);
    x.insert(40);
    x.insert(30);
    x.insert(59);
    x.insert(61);
    x.root.printTree(x.root);


}

ありがとう

4

1 に答える 1

1

Comparableオブジェクトを渡す代わりに、 inを渡すことができますinsert()。Integer、String などの標準型は、すでに Conparable インターフェイスを実装しています。

を使用する代わりにif (a <b) を呼び出します

compareTo(a,b);

Comparable の Java ドキュメントを参照してください。

何らかの理由で to を渡すことにとどまりたい場合は、ObjecttoStringinsert()を使用せずにオブジェクトのクラスをチェックしてからキャストすることで解決することもできます。

if (object instanceof Integer) {
    int val = ((Integer) object).intValue();
    // now compare 
} else if (object instance of String) {
     String val .....
    // use val.compareTo()
}
于 2013-02-10T15:18:29.093 に答える