The code checks the collection for an element, but in the if else block, in any case, isContains gets a value, why does eclipse isContains that isContains may not be initialized?

 public boolean isContains(ArrayList<String> list, String s) { String s1 = ""; String s2 = s.substring(6); boolean isContains; for (int i = 0; i < list.size(); i++) { s1 = list.get(i).substring(6); if (s1 == s2) { isContains = true; } else { isContains = false; } } return isContains; } 

this is the method in which I call the check

 public ArrayList<String> getProductListWithoutDuplicateGoods() { listWithoutDuplicates = new ArrayList<String>(); String s; for (int i = 0; i < sortedProduct.size(); i++) { s = sortedProduct.get(i); if (isContains(listWithoutDuplicates, s) == false) { listWithoutDuplicates.add(s); } } return listWithoutDuplicates; } 
  • four
    list.size() may be zero. - post_zeew pm
  • assumed such, forcibly stuffed there data, no effect - Eugene
  • four
    Do you distinguish between compilation and execution? The compiler does not know what data will be in runtime. - Sergey Gornostaev
  • @SergeyGornostaev, the fact is that if nothing is assigned to a variable in the place where it is declared, then the execution crashes, and the log says that the variable is not initialized - Evgeny
  • one
    not compilation, but compilation. Be careful with terms. - Igor

2 answers 2

Because your isContains is a local variable. A local variable cannot be uninitialized (they have no default value). And the check of this value occurs at compile time, and not in runtime. Read articles about variables. You will understand 10 minutes, but you can find much more interesting and necessary information in them than I will tell here) For an example, you can see the article with javaRush, as for me there is quite intelligible and simple language there everything is written. Here is a link to this article - https://javarush.ru/groups/posts/609-prisvaivanie-i-inicializacija-v-java

    I do not want to ask now how this list appeared in your collection. Perhaps it was necessary to parse it initially and lead to a form in which it would be convenient, safe to work with it (I’m generally silent about resources). What this substring (6) method does I suppose you know. And if your number is not 5-digit, it is also on your conscience. In any case, if you already wanted to do such a check with your hands, then, as for me, you should do something like this ...

     public boolean isContains(final Collection<String> list, final String s) { return list.stream().anyMatch(c->c.substring(6).equals(s)); }