齐天大圣
齐天大圣

Reputation: 1189

Java: how to access inner class's own type

I'm trying to implement a basic symbol table using array.

When I try to implement a get method whose return type is defined in my inner class, but java does not allow me to do that. H

How can i achieve that?

ERROR: cannot resolve symbol 'Key'

public class ST2 {   
    Item[] items;
    int N; 

    public class Item<Key extends Comparable, Value>{

        public Key key;
        public Value value;

        public Item(Key key, Value value){
            this.key = key;
            this.value = value;
        }

        //Some other methods.
    }    

    public ST2(int capacity){
        items = (Item[])new Object[capacity];
    }

    //Some other Method

    public Key get(Key key){    //ERROR HERE: cannot resolve symbol 'Key'
            return items[some_index].key;
    }

Upvotes: 0

Views: 81

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170278

You need to define the Key on ST2, not on Item:

public class ST2<K extends Comparable<K>, V> {

  Item[] items;
  int N;


  public class Item {

    public K key;
    public V value;

    public Item(K key, V value) {
      this.key = key;
      this.value = value;
    }
  }

  public ST2(int capacity) {
    items = (Item[]) new Object[capacity];
  }

  public K get(int index) {
    return items[index].key;
  }
}

Also, generics are usually single letters.

I assume that you're doing this as some sort of exercise/homework, because there already is a Java class that maps (comparable) keys to values: http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

Upvotes: 4

Related Questions