Spire
Spire

Reputation: 31

Treemap Constructor

Is the way I am trying to setup my treemap constructor correct?

import java.util.TreeMap ;

public class Table<K extends Comparable<K>, T> { //K = Key, T = Item

    TreeMap<K, T> tm;

    public Table<K, T> () {
        tm = new TreeMap<K, T>();
    }


    public boolean isEmpty() {
        return tm.isEmpty();
    }

    public int size() {
        return tm.size();
    }

    public void tableInsert(K key, T item) throws TableException {
        tm.put(key, item);
    }

    public boolean tableDelete(K key) {
        if (tm.containsKey(key)) {
            tm.remove(key);
            return true;
        } else {
            return false;
        }
    }

    public T tableRetreive(K key) {
        return tm.get(key);
    } //return null if not found

    public void printTable() {
        TreeMap<K, T> tmclone = (TreeMap<K, T>) tm.clone();
        while (!tmclone.isEmpty()) {
            System.out.println(tmclone.pollFirstEntry());
        }


    } //print in search key order
}

I have another class that will create students, and with the put method will insert into a new map tree.. but the compiler says it was expecting a different character. Also, is the proper way to call the constructor is to input TreeMap blah<K,T> = new TreeMap correct?

Upvotes: 0

Views: 1683

Answers (2)

clstrfsck
clstrfsck

Reputation: 14847

This code here:

public Table<K, T> () {
    tm = new TreeMap<K, T>();
}

needs to change to this:

public Table() {
    tm = new TreeMap<K, T>();
}

Otherwise all good.

Upvotes: 1

TayTay
TayTay

Reputation: 7170

If you are asking if the initialization in the constructor is functional(?), yes. You could also make an initializer above the constructor like this:

public class Table <K extends Comparable<K>, T> { //K = Key, T = Item
     TreeMap<K,T> tm;

     { //Initializer
          tm = new TreeMap<K,T>();
     }

     public Table<K,T>() {
         //Your constructor here
     }

     //Other methods...
}

As far as the second part of your question, there is far too little based on your description to diagnose the issue without seeing some more code and getting more details.

Upvotes: 0

Related Questions