0

Folks, I'm writing a resource manager which can manager different types of resources. Resources can be integers or some custom types. So, I defined an interface like this:

public interface ResourceManagerInterface<R> {
    /**
     * allocateResource:
     * Allocate a resource from the resource pool
     * @return
     */
    R allocateResource() throws ResourceUnavailableException;

    /**
     * freeResource:
     * Deallocate/Return/Free a resource and make it available in the pool.
     * @param resource
     */
    void freeResource(R resource) throws InvalidResourceException;
}

One of the implementors of this interface manages resource of type "int". Since I could not do:

public class NumericResourceManager implements ResourceManagerInterface<int>

I ended up doing:

public class NumericResourceManager implements ResourceManagerInterface<Integer> 

Note: used "Integer" instead of "int".

I had a piece of code like this:

@Override
    public Integer allocateResource() throws ResourceUnavailableException {
        try {
            return internalToExternal(firstAvailableResource());
        } catch (ResourceUnavailableException e) {
            throw e;
        }
    }

The function internalToExternal() returns an "int" and NOT an "Integer".

Questions: 1. Is there an automatic conversion from "int" to "Integer"?

  1. I use the interface like below:

    int someint = someManager.allocateResource();

That is, I'm getting the return value in an "int" and not "Integer". This is also working fine.

Since it works, I'm a bit confused if this is safe and I can leave this as is?

Thanks for your time.

SimpleCoder
  • 1,101
  • 2
  • 10
  • 21
  • This is called [Autoboxing](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html) – tkausl Jan 31 '19 at 00:49
  • This [question](https://stackoverflow.com/questions/27647407/why-do-we-use-autoboxing-and-unboxing-in-java?rq=1) has some additional good information. – Robby Cornelissen Jan 31 '19 at 01:00

1 Answers1

1

Yes, the conversion from Integer to int will happen automatically as was mentioned in the comments. This is called (automatic) unboxing.

However, if the Integer to be unboxed is null, the unboxing will throw a NullPointerException. So keep that in mind for your other code.

machfour
  • 1,929
  • 2
  • 14
  • 21