java – what are the correct uses of contains; equal's; and ==? to compare objects, Integers, Int, Strings..?

Question:

what are the correct uses of contains; equal's; and ==? to compare objects, Integers, Int, Strings..? I know that sometimes they can be used in the wrong way but I don't know how to do it right.. Thank you

Answer:

In Java, == only compares two references (not primitives), 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 equal.

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 of the same string constants (mainly string literals, but also combinations of string constants via 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 refer to the same string, because y is a compile-time constant 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.");

Instead 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");

OS source:


Contains() :

About the Contains() method it checks if a particular string is a part of another string 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");

Ver: Arrays # asList (T …) y ArrayList # contains (Object)

Scroll to Top