简体   繁体   中英

Is there a way to achieve implicit type cast or conversion in java

I wanted to create a method that takes an enum and uses it directly in an computation

  private static int getEntries(List<Integer> vector, Sign sign)
  {
    //assert isPrimitiveTypeCompliant(vector) : "Vector has null components!";
    int entries = 0;

    for (Integer entry : vector)
      if (entry * sign > 0) // does not compile
        entries++;

    return entries;
  }

I thought sth. like that was possible, since I assumed System.out.println(Object) does implicit type conversion, too. Which it doesn't, it uses following approach:

 public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

 public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
    }

Question

So is it possible to achieve this in java? Or is this reserved to C++ and overloading of operators? What are the common workarounds? Utility/Adapter classes that do the work?


Btw, I eventually ended up with this approach

  private enum Sign
  {
    POSITIVE(+1), NEGATIVE(-1);

    private int sign;

    private Sign(int sign)
    {
      this.sign = sign;
    }

    public int process(int n)
    {
      if (n * sign > 0)
      {
        return n;
      }
      return 0;
    }
  }

  private static int getEntries(List<Integer> vector, Sign sign)
  {
    //assert isPrimitiveTypeCompliant(vector) : "Vector has null components";
    int entries = 0;

    for (Integer entry : vector)
      entries += sign.process(entry);

    return entries;
  }

Yes, it is possible to achieve it. In fact, you did in the second piece of code.

Java doesn't have operator overloading or implicit conversions (beyond numerical conversions and "widening" type casts). So, there is no way of allowing syntax like entry * sign (except the one you used).

What do you mean workarounds? This is not a problem. It is a language design decision. And you already arrived successfully to the appropriate Java idiom.

why not just use the int value of the sign

if (entry * sign.value > 0)



enum Sign

    public final int value;

I think for this case it would work better for you to use final static variables.

public final class Sign {
    public final static int POSITIVE = 1;
    public final static int NEGATIVE = -1;

    private Sign() {
    }
}

Then you can use Sign.POSITIVE and Sign.NEGATIVE for the operations you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM