从具有给定行/列/表号的数据库样式表中获取数据的最佳方法-Java
我有几个假设的二维表,从中获取数据。我需要创建一个方法,该方法将接收表id和所需项的“坐标”,并返回该项。到目前为止,我已经尝试使用多层从具有给定行/列/表号的数据库样式表中获取数据的最佳方法-Java,java,database,switch-statement,Java,Database,Switch Statement,我有几个假设的二维表,从中获取数据。我需要创建一个方法,该方法将接收表id和所需项的“坐标”,并返回该项。到目前为止,我已经尝试使用多层switches,但我想知道是否有更好的方法来实现这一点,因为switch代码似乎太长,不是最佳解决方案。任何帮助都将不胜感激 我的代码是什么样子的: switch(tableId) { case "table 1": switch(top) { case "whatever": s
switch
es,但我想知道是否有更好的方法来实现这一点,因为switch代码似乎太长,不是最佳解决方案。任何帮助都将不胜感激
我的代码是什么样子的:
switch(tableId) {
case "table 1":
switch(top) {
case "whatever":
switch(side) {
// et cetera
case "table 2":
// etc
}
您必须以一种更面向对象的方式重写所有内容,在Java中实现这一点的一种聪明方法是使用一些“调优”枚举:
enum activity { WHATEVER, SOMETHINGELSE } //Use the same principle as in the enum below ...
enum tables {
TABLE1(activity.WHATEVER),
TABLE2(activity.SOMETHINGELSE),
private activity activity;
tables(activity activity) {
this.activity = activity;
}
public activity activity() {
return this.activity;
}
}
为每个所需级别创建所有所需的枚举后,可以使用以下“技巧”来避免长的多级开关条件语句:
String tableId = ...
//Load the table
tables table = tables.valueOf(tableId);
//Call the related attached activity ...
table.activity();
当然,enum元素必须与要截取的变量名同名(与if或switch语句的检查条件相同)。
另一个类似的结果可以通过使用映射而不是枚举来实现。。。
请查看,以了解更多信息。使用
创建一个界面可搜索表
:
public interface SearchableTable<T> {
T getItem(int x, int y);
}
如果必须获取表id而不是表,只需将表id映射到相关的可搜索表,如下所示:
public class TableUtils {
public static <T> T getItem(SearchableTable<T> table, int x, int y) {
return table.getItem(x, y);
}
}
public class TableUtils {
private static Map<Long, SearchableTable> tableIdToSearchableTable;
public static <T> T getItem(SearchableTable<T> table, int x, int y) {
return table.getItem(x, y);
}
}
只是想知道,在没有枚举的其他语言(例如JavaScript)中,我如何才能做到这一点?您可以使用映射或字典获得类似的结果,或者您可以创建一个类似于java枚举的类(请记住,java枚举不是真正的枚举,而是一个“特殊”类)。它允许您调用
getItem
,而无需在不同的表之间切换。这就像说“我不管这是哪个表,我只想确保它有一个getItem
方法并调用它”(如果解释是伪的,很抱歉:))好的,所以我创建了接口,但当我尝试将它实现到表中时,它告诉我它需要一个。我编写了public enum table 1实现了searchable table
,但它仍然需要一个。救命啊!那么,请参见编辑我的答案,您的表1
应该是什么样子。我不知道你说的
是什么意思。请注意,SearchableTable
的参数化类型是T
(一个字母),而不是一个单词。。。那么标识符是从哪里来的呢?哦,我明白为什么了-我试图将我的表设置为枚举,而您有一个类。我现在换了一门课。
public class TableUtils {
private static Map<Long, SearchableTable> tableIdToSearchableTable;
public static <T> T getItem(SearchableTable<T> table, int x, int y) {
return table.getItem(x, y);
}
}
public class Table1 implements SearchableTable<String> {
public String getItem(int x, int y) {
// use x and y to fetch the item friom the 2-dimensional data structure
}
}