简体   繁体   English

如何将任何对象类型传入方法? 爪哇

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

Note: the NPE error has been fixed注意:NPE 错误已修复

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.它可以按名称或对象的任何其他唯一内容,但不能按类型或值,因为在 HashMap 中可能存在具有相同类型或值的其他对象。

In TOES.java:在 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:在 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.当 TOESTest1 运行时,它显示最后一个 println 的错误和 val 方法中的返回。

The output should be:输出应该是:

3
7

(Ignore the weird names, TOES is an acronym) (忽略奇怪的名字,TOES 是首字母缩写词)

I am new to java, but not new to programming (I know C++), so...我是 Java 新手,但不是编程新手(我知道 C++),所以...

You can do that by using a Map and the Optional class implemented since Java 8.您可以通过使用 Map 和自 Java 8 以来实现的 Optional 类来做到这一点。

The Map is gonna contain the String identifier and the Object you want to pass. Map 将包含字符串标识符和您要传递的对象。

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 .要在 Optional 中获取对象,您可以使用Optional.get()方法,如果有,它将返回对象,否则返回null

<?> is a shorthand for <? extends Object> <?><? extends Object> <? extends Object> , it's also known as an unbounded wildcard. <? extends Object> ,它也被称为无界通配符。 So you can specify any type of object in your generic.所以你可以在你的泛型中指定任何类型的对象。

int doesn't inherit from Object in Java. int不从 Java 中的 Object 继承。 You can cast your int s to Integer s, and then you'll be able to pass them to a function that takes Objects.您可以将int s 转换为Integer s,然后您就可以将它们传递给一个接受对象的函数。

See also: Is int an object in Java另请参阅: 在 Java 中 int 是一个对象吗

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.因为您是说您是 Java 新手并了解 C++,所以 Java 与 C++ 的最大区别在于 Java 中的一切都是指针,本机除外。 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. a仍然没有初始化,也没有指向任何东西,这与用 Empty Constructor 初始化的 C++ 不同。

update更新

Of course you are getting NPE, you haven't initialized the TOE.当然,您正在获得 NPE,您还没有初始化 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使用IdentityHashMap而不是使用 HashMap

... in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). ...在 IdentityHashMap 中,两个键 k1 和 k2 被认为相等当且仅当 (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)).) (在普通 Map 实现(如 HashMap)中,当且仅当 (k1==null ? k2==null : k1.equals(k2)) 时,两个键 k1 和 k2 被认为是相等的。)

Instead of comparing equality with .equals method, it's comparing with the reference (pointer address) of the object.它不是与.equals方法比较相等性,而是与.equals的引用(指针地址)进行比较。

There is also a warning thought.还有一个警告的想法。

This class is not a general-purpose Map implementation!这个类不是一个通用的 Map 实现! 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.虽然这个类实现了 Map 接口,但它故意违反了 Map 的一般约定,即在比较对象时强制使用 equals 方法。 This class is designed for use only in the rare cases wherein reference-equality semantics are required.此类设计用于仅在需要引用相等语义的极少数情况下使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JAva:如何将自定义对象类型作为参数传递给方法,并返回相同的自定义对象类型值 - JAva:How to pass a custom object type as a parameter to a method and return the same custom object type value back 如何为同一方法传递不同的 object 类型,而不是在 java 中编写具有相同功能和返回类型的两个方法 - How to pass different object type for same method instead of writing two methods with same functionality and return type in java Java-如何将泛型类型的类传递给方法 - Java - How to pass the class of a generic type into a method Java-如何传入类型Class <A<B> &gt;到方法 - Java - How to pass in type Class<A<B>> to method 如何在Java中将类型作为方法参数传递 - How to pass a type as a method parameter in Java Java将对象传递给方法 - Java Pass object to method 如何将要创建的对象作为 Java 方法的参数传递? - How to pass a object to be created as a parameter for a method in Java? 如何将 object 传递给在 java 中使用反射的方法 - How to pass an object to a method using reflection in java Java方法获取任何类型的摆动对象的宽度? - Java method for getting width of swing object of any type? java toString方法能够读取内容内的任何类型对象吗? - Is java toString method capable in reading any type object inside content?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM