a pesar de ser cierto que el operador == no se utiliza para comparar instancias, esto es efectivo siempre y cuando se desee comparar el contenido de los objetos.
The == operator returns true if the two handles on the left and right sides refer to the same location in memory. The function Object.equals() is intended to return true if two handles refer to logically equivalent instances.
Comparing with the == OperatorThe == operator works on String object references. If two String variables point to the same object in memory, the comparison returns a true result. Otherwise, the comparison returns false, regardless whether the text has the same character values. The == operator does not compare actual char data. Without this clarification, you might be surprised that the following code snippet prints The strings are unequal.String name1 = "Michèle";String name2 = new String("Michèle");if (name1 == name2) { System.out.println("The strings are equal.");} else { System.out.println("The strings are unequal.");} The Java platform creates an internal pool for string literals and constants. String literals and constants that have the exact same char values and length will exist exactly once in the pool. Comparisons of String literals and constants with the same char values will always be equal.Comparing with the equals MethodThe equals method compares the actual char content of two strings. This method returns true when two String objects hold char data with the same values. This code sample prints The strings are equal.String name1 = "Michèle";String name2 = new String("Michèle");if (name1.equals(name2) { System.out.println("The strings are equal.");} else { System.out.println("The strings are unequal.");}
Sin embargo, un boton llamado "aceptar" es unico, asi lo declaras, no puedes tener dos botones en una misma clase llamados"aceptar".
El equals devuelve un boolean, para comprobar si hablas de dos objetos iguales.
logicamente el if no sirve, porque apunta a una dirección de memoria, la cual seria distinta a pesar que el objeto tenga los mismos campos.
JButton a= new JButton("boton");JButton b= new JButton("boton");System.out.println((a==b )+" "+a.equals(b ));
Código: Text public class Shadowing { private int x; public static void main(String[] args) { x = 6 int x;// variable repetida x = 5; // no existe error System.out.println("x = " +x); } }
Código: Text public class A { private String nombre; private String apellido; public A() { nombre = new String(); apellido = new String(); } public A(String nombre, String apellido) { this(); this.nombre = nombre; this.apellido = apellido; } }
Lo de equals lo comprendo, sé que compara referencias en la memoria.