gpt4 book ai didi

Java-语义分析: Implementing a hash table with a key and multiple value

转载 作者:行者123 更新时间:2023-12-02 02:19:11 24 4
gpt4 key购买 nike

在语义分析中,最流行的方法或数据结构之一是哈希表。实现哈希表相对容易,但是阅读本文 peresentation这对我来说很复杂——我不知道我是否正确。根据演示,如何使用具有多个值的标记(key)实现符号表?

我的想法是创建一个下表:

给定输入字符串:
VAR abc, b, c AS INT

   | symbol | datatype | value |
-----------------------------
| VAR | keyword | null |
| abc | INT | null |
| b | INT | null |
| c | INT | null |
| AS | keyword | null |
| CHAR | keyword | null |

VAR x, w_23='w' AS CHAR

   | symbol | datatype | value |
-----------------------------
| VAR | keyword | null |
| x | CHAR | null |
| w_23 | CHAR | 'w' |
| AS | keyword | null |
| CHAR | keyword | null |

所以,假设我有一个变量a,如果我查找(a),那么它应该是错误的,因为查看表key a 不存在。另外,如果 w_23=10 也应该是一个错误,因为 w_23CHAR 类型,通常它只是一个类型检查。

我的问题是,是否可以创建一个像上面那样的符号表?如果可以,我该如何实现一个以 symbol 作为 key数据类型和值作为值?.

最佳答案

我会使用基于泛型的方法。

首先定义一个像这样的泛型类:

public abstract class GenericEntry<T> {
protected T value;

@SuppressWarnings("unchecked")
public Class<? extends T> getDatatype() {
return (Class<? extends T>) value.getClass();
}

public T getValue() {
return value;
}

public void setValue(T value) {
this.value = value;
}
}

然后定义 Material 类。一个用于角色,例如:

public class CharacterEntry extends GenericEntry<Character> { }

还有一个整数:

public class IntegerEntry extends GenericEntry<Integer> { }

还有一些测试的主要部分:

public class Main {
public static void main(String[] args) {
HashMap<String, GenericEntry<?>> myMap = new HashMap<>();

CharacterEntry characterEntry = new CharacterEntry();
characterEntry.setValue('c');
myMap.put("key1", characterEntry);

IntegerEntry integerEntry = new IntegerEntry();
integerEntry.setValue(3);
myMap.put("key2", integerEntry);

GenericEntry<?> entry1 = myMap.get("key1");
System.out.println(entry1.getDatatype());
System.out.println(entry1.getValue());

GenericEntry<?> entry2 = myMap.get("key2");
System.out.println(entry2.getDatatype());
System.out.println(entry2.getValue());
}
}

其输出是:

class java.lang.Character
c
class java.lang.Integer
3

正如您从@stephen-c的回答中看到的,方法可能有所不同,但无论如何您都必须定义一个包含数据类型和值的类。

关于Java-语义分析: Implementing a hash table with a key and multiple value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48766253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com