Java 在数组中查找元素时,何时应生成else?

Java 在数组中查找元素时,何时应生成else?,java,loops,while-loop,return,Java,Loops,While Loop,Return,我使用带有计数器的while循环来查找数组中的元素。我将检查返回的元素是否等于数组的长度,是否找不到该元素。循环是这样的 int i = 0; int returned; boolean found = false; while(i < words.length && !found){ WordInText check = new WordInText(w); if(check.equals(words[i])

我使用带有计数器的while循环来查找数组中的元素。我将检查返回的元素是否等于数组的长度,是否找不到该元素。循环是这样的

    int i = 0;
    int returned;
    boolean found = false;
    while(i < words.length && !found){
        WordInText check = new WordInText(w);
        if(check.equals(words[i])){
            found = true;
        }
        else{
            i++;
        }
   return i
inti=0;
返回int;
布尔值=false;
while(我
我想知道的是,在每种情况下,做以下事情是否比做其他事情更好

int i = 0;
    int returned;
    boolean found = false;
    while(i < words.length && !found){
        WordInText check = new WordInText(w);
        if(check.equals(words[i])){
            found = true;
        }
        i++;
   }
   if(!found)
        i++;
   return i-1
inti=0;
返回int;
布尔值=false;
while(我

我觉得第二个更有效,因为它不必检查每个循环的条件,如果数组真的很长,则需要做很多工作。但我不确定何时决定每个循环,因为第二个循环看起来很难看,也不直观。

用这样的方法提取代码

public int contains(....) {
  int i = -1;
  while(i < words.length){
     WordInText check = new WordInText(w);
     if(check.equals(words[i])){
         return i;
     }
   i++;
  }
 return i;
}
public int包含(…){
int i=-1;
while(i

不需要额外的变量和更清晰的代码结构

有多种可能的重构可以避免这个问题,但我将尝试按原样回答您的问题:

  • else
    不花费任何成本:它只是一个块,当且仅当
    if
    的条件计算为
    false
    时才会执行
  • 这很容易被任何人理解

即使它看起来不是最漂亮的,我也没有理由避免它。在您的第二个代码中,不仅引入了额外的指令,而且还很难理解,因为您必须了解在找不到元素时为什么需要增加索引。

我不认为您需要使用else部分或其他if条件来检查whet她是否已找到,因为您已经在while循环中检查了条件

int i = 0;
int returned;
boolean found = false;
while(i < words.length && !found){
    WordInText check = new WordInText(w);
    if(check.equals(words[i])){
        found = true;
    }
    i++;
}
return i;
inti=0;
返回int;
布尔值=false;
while(我
因此,在这里循环将继续,直到find的值变为true(意味着直到找到所需的元素。然后在下一次迭代中,它将检查找到的值是否为false。因为它不再为false,所以循环将不会执行,并且返回i。
在那里,您可以检查i的值,并确定是否找到元素。

更好的方法是使用
哈希集
。什么是
w
WordInText
?我问它们是什么,您说“是”…@user1803551抱歉,这是一个字符串