Ternary operator '?'

0

The ternary operator ? java is giving me error using it in the following way:

ArrayList <String> titleTabs= new ArrayList<>();
ArrayList <String> countTitleTabs= new ArrayList<>();

public ViewPagerAdapter(ArrayList<String> titleTabs, ArrayList<String> countTitleTabs) {

        titleTabs.get(0).isEmpty() ? this.titleTabs.add(0,"----") : this.titleTabs.add(0,titleTabs.get(0));

}

What am I doing wrong?

    
asked by borjis 30.01.2017 в 13:20
source

3 answers

7

The ternary operator ? is also known as conditional . So, use it to assign a value based on a given condition.

In your case it would be:

this.titleTabs.add(0, (titleTabs.get(0).isEmpty() ? "----" : titleTabs.get(0)));

Since the first value is the same in both cases, only the second changes and the construction form of that operator is:

valorDeseado = (condición)? valorSiSeCumple : valorSi_NO_SeCumple;
    
answered by 30.01.2017 / 13:28
source
3

The ternary operator is used to return a value, not to perform operations. Your code should be something like this:

 valor = titleTabs.get(0).isEmpty()?"----":titleTabs.get(0);
 this.titleTabs.add(0,valor);

or

this.titleTabs.add(0,titleTabs.get(0).isEmpty()?"----":titleTabs.get(0));
    
answered by 30.01.2017 в 13:24
1

In the cases that I had to use it, I used it as follows:

algunObjetoJson.addProperty("accion",(null != algo.getNombre() ? "<a href="">HolaJuan</a>" : "<a href="">HolaAlguien</a>"));

Both ? and : must assign a value followed by them.

    
answered by 30.01.2017 в 15:47