检查静态数组中是否有值:Java
我有以下课程:检查静态数组中是否有值:Java,java,if-statement,compare,Java,If Statement,Compare,我有以下课程: public class ValueHolder { private String columnName; private int width; private String defaultColumnStyle; public String getDefaultColumnStyle() { return defaultColumnStyle; } public void setDefaultColumnSty
public class ValueHolder {
private String columnName;
private int width;
private String defaultColumnStyle;
public String getDefaultColumnStyle() {
return defaultColumnStyle;
}
public void setDefaultColumnStyle(String defaultColumnStyle) {
this.defaultColumnStyle = defaultColumnStyle;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public ValueHolder(String columnName, int width, String cellStyle) {
this.columnName = columnName;
this.width = width;
}
public ValueHolder(String columnName, int width, String cellStyle, String defaultColumnStyle) {
this(columnName, width, cellStyle, defaultColumnStyle, null);
}
public ValueHolder(String columnName, int width, String cellStyle, String defaultColumnStyle, String dataFormat) {
this.columnName = columnName;
this.width = width;
this.defaultColumnStyle = defaultColumnStyle;
}
}
以及以下
public class StaticArrayValues {
public static ValueHolder[] TEST_VALUES = new ValueHolder[] {
new ValueHolder("test Name", 4498, "testvalue"), new ValueHolder("Last Name", 4498, "testvalue"),
new ValueHolder("test ID", 4498, "testvalue"), new ValueHolder("ID Value", 4498, "testvalue") };
public static void main(String[] args) {
String testValue= "First Name";
// How do i check if testValue is there in TEST_VALUES
/*if(){
}*/
}
}
如何检查TEST_值中是否有“First Name”
我确信这是一个基本问题,但我仍然无法找到解决方法:(
有人能帮我吗?在数组上循环
测试\u值
并检查列名
是否等于测试值
for(int i = 0 ; i < TEST_VALUES.length ; i++){
if(TEST_VALUES[i].getColumnName().equals(testValue)){
//do whatever you want
break; //if you to exit the loop and done comparing
}
}
for(int i=0;i
您必须迭代数组
boolean isPresent = false;
for(ValueHolder valueHolder: TEST_VALUES){
if(valueHolder.getColumnName().equals(testValue)){
isPresent = true;
break;
}
}
一些额外的想法,
如果您正在执行大量这些操作(搜索某个特定字段中是否存在值),则可以创建HashMap
(HashMap)并将columnName
作为键,将ValueHolder对象作为值,这将为查找提供恒定的时间复杂度,而不是在遍历整个列表时的线性时间复杂度。建议1)某种形式的循环2)使用希望执行的逻辑分离查找
ValueHolder found = null;
for (ValueHolder each : TEST_VALUES) {
if (each.getColumnName().equals(testValue)) {
found = each;
break;
}
}
if (found != null) {
// do stuff
}
您的代码建议使用底层数据库。。。是吗?如果是这样,您可能应该在该级别进行查询,而不是在应用程序逻辑中进行查询?