检查静态数组中是否存在值

问题描述 投票:0回答:3

我有以下课程:

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_VALUES= 中是否存在“名字”?

java if-statement compare
3个回答
2
投票

你必须迭代数组

boolean isPresent = false;
for(ValueHolder valueHolder: TEST_VALUES){
  if(valueHolder.getColumnName().equals(testValue)){
     isPresent = true;
     break;
  }
}

一些额外的想法, 如果你做了很多这样的事情(搜索某个特定字段中是否存在某个值),那么你可以创建一个

HashMap
(HashMap) 并将
columnName
作为键,将 ValueHolder 对象作为值,这将为你提供查找中的时间复杂度是恒定的,而不是迭代整个列表时的线性时间复杂度。


0
投票

在数组

TEST_VALUES
上循环并检查
columnName
是否等于
testValue

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
    }
}

0
投票

推荐 1) 某种形式的循环 2) 将结果与您希望执行的逻辑分开......

ValueHolder found = null;
for (ValueHolder each : TEST_VALUES) {
    if (each.getColumnName().equals(testValue)) {
       found = each;
       break;
    }
}
if (found != null) {
   // do stuff
}
© www.soinside.com 2019 - 2024. All rights reserved.