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

时间:2015-11-11 07:04:53

标签: java if-statement compare

我有以下课程:

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吗?

我确信这是基本问题,但我仍然无法找到方法:(。

有人可以帮我吗?

3 个答案:

答案 0 :(得分:2)

你必须迭代数组

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

一些额外的好处, 如果您正在执行大量这些操作(搜索某个特定字段中是否存在值),则可以创建HashMap(HashMap< String,ValueHolder>)并将columnName作为键和ValueHolder对象作为值,这将使您在查找时保持恒定的时间复杂度,而不是在迭代遍历整个列表时的线性时间复杂度。

答案 1 :(得分: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
    }
}

答案 2 :(得分:0)

推荐1)某种形式的循环2)用你想要执行的逻辑分离出这个发现......

ValueHolder found = null;
for (ValueHolder each : TEST_VALUES) {
    if (each.getColumnName().equals(testValue)) {
       found = each;
       break;
    }
}
if (found != null) {
   // do stuff
}