what are the correct uses of contains; equals; e ==? to compare objects, Integers, Int, Strings ..?

4

what are the correct uses of contains; equals; e ==? to compare objects, Integers, Int, Strings ..? I know that sometimes they can be used the wrong way but I do not know well .. Thanks

    
asked by MaRiAnO 12.05.2018 в 17:14
source

1 answer

4

In Java, == only compares two references (not primitive), that is, it tests whether the two operands refer to the same object.

However, the equals method can be overridden, so two different objects can be the same.

For example:

String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });

System.out.println(x == y); // false
System.out.println(x.equals(y)); // true

Also, it's worth keeping in mind that two equal string constants (mainly string literals, but also combinations of string constants by concatenation) will end up referring to the same string.

For example:

String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!

Here x & y make references to the same string, because y is a constant at compile time equal to "hello" .

Another Example:

Integer i = 100;
Integer p = 100;
if (i == p)  System.out.println("i y p son lo mismo.");
if(i.equals(p))  System.out.println("i y p contienen el mismo valor.");

On the other hand, if so:

Integer i = new Integer (100); 
Integer p = new Integer (100); 
if (i == p) System.out.println("i y p son el mismo objeto"); 
if (i.equals(p)) System.out.println("i y p contienen el mismo valor");
  

SO Source:

     

Contains () :

About the method Contains() this checks if a particular string is a part of another chain or not.

  

Returns true if and only if this string contains the specified sequence of char values.

Example:

String[] arreglo= new String[] { "Lunes", "Martes" };
String valor= Arrays.toString(arreglo);
boolean resultado = string.contains("Martes");

But I would recommend:

String[] arreglo= new String[] { "Lunes", "Martes" };
List<String> lista= Arrays.asList(arreglo);
boolean resultado = stringList.contains("Martes");
  

See: Arrays # asList (T ...) and ArrayList # contains (Object)

    
answered by 12.05.2018 в 17:25