调用另一个类的泛型函数时程序崩溃

时间:2022-03-12 06:51:02

When I calling "getFirstKey" inside class B is OK, but from class A the program crash.

当我在B类中调用“getFirstKey”时可以,但是从A类程序崩溃。

public class B {

    public static Object getFirstKey(Map m) {
        return =  m.keySet().toArray()[0];
    }

    public static void EnsureTest(Map m){
        Object myKey;

        // print first key
        myKey = getFirstKey(m);
        System.out.println("Lowest key Stored in Map is.: " + myKey);
    }
}

public class A {
    private static Map<Long, YourDataClass> map;

    public void print() {
        Log.d("TEMP", "1");
        CreateTempMap();
        Log.d("TEMP", "2");
        System.out.println(map);
        Log.d("TEMP", "3");
        B.EnsureTest(map);
        Log.d("TEMP", "4");
        Object myKey;
        myKey = B.getFirstKey();
        Log.d("TEMP", "5");
    }
}

How can I make it safe to call the method from class A?

如何从A类调用方法安全?

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.examples.android.calendar/com.examples.android.calendar.CalendarView}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
            at android.app.ActivityThread.access$600(ActivityThread.java:156)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:5297)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.examples.android.calendar.B.getFirstKey(B.java:36)

EDIT: Added Error log to make it more clear!

编辑:添加错误日志,使其更清晰!

1 个解决方案

#1


You are not passing in a Map with your call of getFirstKey from class A.

您没有通过从A类调用getFirstKey传入Map。

You are doing the call correctly when it is being called from class B

从B类调用时,您正在正确地进行调用

#1


You are not passing in a Map with your call of getFirstKey from class A.

您没有通过从A类调用getFirstKey传入Map。

You are doing the call correctly when it is being called from class B

从B类调用时,您正在正确地进行调用