简体   繁体   中英

How to pass in any Object type into a method? Java

Note: the NPE error has been fixed

I need a way to identify an Object when it is passed into a method. It can be by name or anything else unique to the Object, but not by type or value, since there may be other Objects with the same type or value in the HashMap.

In TOES.java:

import java.util.HashMap;

public class TOES{

    private HashMap<Object, HashMap<String, Object>> TOES = new HashMap<Object, HashMap<String, Object>>();

    public void add(Object foot, String tag, Object data){
        HashMap<String, Object> TOE = TOES.get(foot);
                if(TOE == null){
                         TOE = new HashMap<String, Object>;
                 }
        TOE.put(tag, data);
        TOES.put(foot, TOE);
    }

    public Object val(Object foot, String tag){
        return TOES.get(foot).get(tag);
    }

}

In TOESTest1.java:

public class TOESTest1{

    public static void main(String[] arg){
        TOES Toes = new TOES();
        Integer potatoes = 5;
        Integer eyes = 7;
        String tagname = "eyes";
        Toes.add(potatoes,tagname,eyes);
           potatoes = 3;
        System.out.println(potatoes);
        System.out.println(Toes.val(potatoes, "eyes"));
    }

}

When TOESTest1 is run, it shows an error for the last println and the return in the val method.

The output should be:

3
7

(Ignore the weird names, TOES is an acronym)

I am new to java, but not new to programming (I know C++), so...

You can do that by using a Map and the Optional class implemented since Java 8.

The Map is gonna contain the String identifier and the Object you want to pass.

Map<String, Optional<?>> mapToSendToMethod = new HashMap<String, Optional<?>>();
mapToSendToMethod.put("This is a string", Optional.of("This is a test"));
List<String> ListToSend = new ArrayList<>();
mapToSendToMethod.put("This is a List", Optional.of(ListToSend));
mapToSendToMethod.put("This is a number", Optional.of(123));`
someMethod(mapToSendToMethod);`

to get the object inside Optional you can use the method Optional.get() which it will return the object if there's any, otherwise null .

<?> is a shorthand for <? extends Object> <? extends Object> , it's also known as an unbounded wildcard. So you can specify any type of object in your generic.

int doesn't inherit from Object in Java. You can cast your int s to Integer s, and then you'll be able to pass them to a function that takes Objects.

See also: Is int an object in Java

Because you are saying you are new to Java and know C++, the biggest difference in Java with C++ is in Java everything is pointer, in exception the native. So when you declare

HashMap<Object, String> a;

a still haven't initialized and not pointing to anything, which differ from C++ where it's initialized with Empty Constructor.

update

Of course you are getting NPE, you haven't initialized the TOE. Fix add method like this

public void add(Object foot, String tag, Object data){
    HashMap<String, Object> TOE = TOES.get(foot);
    if (TOE == null) {
        TOE = new HashMap<String, Object>();
    }
    TOE.put(tag, data);
    TOES.put(foot, TOE);
}

end of update

You are looking for equality by reference. Instead of using HashMap, uses IdentityHashMap

... in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)

Instead of comparing equality with .equals method, it's comparing with the reference (pointer address) of the object.

There is also a warning thought.

This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.

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