Can switch be used with objects in java?

0

Hello very afternoon or evening ... my question is the following can you use the switches to compare objects ?? see it this way I have a window with 3 buttons, each button changes the background to a different color could the switch be implemented to know which button will execute the event?

package ClasesInterfaz;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class CreandoMarcoConEventos {

public static void main(String[] args) {

    MarcoEvento miMarco = new MarcoEvento();
    miMarco.setVisible(true);
    miMarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}



}

class MarcoEvento extends JFrame{

MarcoEvento(){

    setSize(400,300);
    setLocation(300,200);
    LaminaEvento laminita = new LaminaEvento();
    add(laminita);
}

}

class LaminaEvento extends JPanel implements ActionListener{

JButton botonazul = new JButton("Boton azul");
JButton botonRojo = new JButton("Boton Rojo");
JButton botonAmarillo = new JButton("Boton amarillo");

public void actionPerformed(ActionEvent e) {

    Object objetoEvento = e.getSource();
    if(objetoEvento==botonazul) {
    setBackground(Color.BLUE);
    }
    else if(objetoEvento==botonRojo) {

        setBackground(Color.RED);
    }
    else {
        setBackground(Color.yellow);
    }
}

LaminaEvento(){
    add(botonRojo);
    add(botonAmarillo);
    add(botonazul);
    botonazul.addActionListener(this);
    botonAmarillo.addActionListener(this);
    botonRojo.addActionListener(this);
}




}

I want to know if it is possible to change the if .. else by switch and if possible, how to do it? thanks in advance.

    
asked by Cesar Quintero 03.02.2018 в 14:45
source

3 answers

0

No, you can not use Switch to compare objects for the same reason that you can not use logical operators (== or! =) to compare objects.

Objects are instances, and the variables that reference them are pointers to those instances. When you compare two objects, you are not comparing if their "value" is identical, you are comparing if they are the same instance, if they are the same object. Or put another way, Java answers if both variables are pointing to the same memory address.

The appropriate way to compare if the value of two objects is the same or different is to use the inherited method ".equals ()", and having implemented it correctly in your class, in the case that it is a personal object that you have created yourself.

You have to be very careful when comparing objects, because there are exceptional cases in which Java appears to give consistent results and make us believe that the comparisons are valid, as is the case with the String or Integer class, but they have a "trick" . In the case of String, Java reuses instances whenever it detects that there are repeated strings, and in the case of Integer, there is a cache in a specific range of numbers to save memory. But even if the comparison seems to give correct results, they are NOT reliable.

    
answered by 04.02.2018 / 00:13
source
2

No, according to language specification for the switch statement:

  

The Expression type must be char, byte, short, int, Character,   Byte, Short, Integer, String or an enumeration type (§8.9), or   an error occurs at compile time.

    
answered by 03.02.2018 в 18:58
0

It is not possible, because, seeing your documentation:

here in its basics comments that * A switch works with the byte, short, char, and int primitive data types * that means that a switch only works with: byte, short, char and integers, only primitive data.

and here is an example of a switch:

public class SwitchDemo {
    public static void main(String[] args) {

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

How does a switch work?

Using Switch

Switch syntax.

The Syntax used by a switch is as follows:

switch (variable)  { 
     case <posible valor> : Instrucciones : break;
     case <posible valor> : Instrucciones : break;
     case <posible valor> : Instrucciones : break;
     case <posible valor> : Instrucciones : break;
     case <posible valor> : Instrucciones : break;
     default : Instrucciones ; 

Given an input variable this is defined followed by the word switch.

A key is opened to initiate the possible values that said variable can take.

The sets of values are initiated with case followed by the possible value of the variable, then a set of instructions is defined that will be executed if the value corresponds to the variable and finally (optional) the word break is used to exit of cycle case.

An optional value is the definition of the default line, whose instructions will be executed in case the switch variable does not match the defined values.

Example of a months switch:

 
public class Meses {
    public static void main(String[] args) {
        int month = 8;
        switch (month) {
            case 1:  System.out.println("Enero"); break;
            case 2:  System.out.println("Febrero"); break;
            case 3:  System.out.println("Marzo"); break;
            case 4:  System.out.println("Abril"); break;
            case 5:  System.out.println("Mayo"); break;
            case 6:  System.out.println("Junio"); break;
            case 7:  System.out.println("Julio"); break;
            case 8:  System.out.println("Agosto"); break;
            case 9:  System.out.println("Septiembre"); break;
            case 10: System.out.println("Octubre"); break;
            case 11: System.out.println("Noviembre"); break;
            case 12: System.out.println("Diciembre"); break;
        }
    }
}

Class Months A primitive with a value of 8 is defined, which is used as a variable for a switch.

Within the switch values from 1 to 12 are defined, which have the instruction to print to the screen the value of the corresponding month.

When the syntax of a switch was described, it was mentioned that the use of break at the end of each declaration (case) was optional, this is due to the possibility that there is more than one value that must execute the same instructions.

source of the above mentioned: source

    
answered by 03.02.2018 в 23:08