Java implements the method of determining whether an element is contained in the sequence list

1. Ideas

1. Define a toFind variable to pass in the element to be found
2. Traverse the entire sequence table and determine whether the current subscript element is equal to toFind
3. If it is equal, return a true, otherwise return false.


2. Diagram


First call the following method to find the length of the sequence table, and then use the for loop to traverse each element.

// 求顺序表的长度
public int size() {
    
    
    // 直接返回元素个数
    return this.usedSize;
}



When traversing to the first element, it is found that the element at this time is 12, which is not equal to toFind, so continue to search.


When i goes to the next element, it is found that it is still not equal to the value of toFind, so continue to look backward.


It is found that the value of subscript i is equal to the value of toFind at this time, so it means that there is an element of toFind in the sequence table,
just return true.

If no element equal to toFind is found after traversing the entire sequence table, it means that there is no such element in the sequence table,
just return false.


When the current i goes to the 3 subscript, it is found to be empty at this time, which means that the sequence table has been traversed.


3. Code

//判定是否包含某个元素 - toFind是我要判定的元素
public boolean contains(int toFind) {
    
    
    //size()方法求的是顺序表的长度
    for (int i = 0; i < this.size(); i++) {
    
    
        if (this.elem[i] == toFind) {
    
    
            return true; //找到了
        }
    }
    return false;///没找到
}

// 求顺序表的长度
public int size() {
    
    
    // 直接返回元素个数
    return this.usedSize;
}



Above are the elements in my current order table.


Judging whether there are two elements 3 and 1000 in the current sequence table, the conclusion can be reached in view of the elements in the above sequence table.
Will first output a true, and then output a false.


You can see that the output is correct at this point.

Guess you like

Origin blog.csdn.net/m0_63033419/article/details/131037879