GVKun编程网logo

使用数组时发生NullPointerException(数组 null)

16

本文将为您提供关于使用数组时发生NullPointerException的详细介绍,我们还将为您解释数组null的相关知识,同时,我们还将为您提供关于android–为什么使用标准BillingSer

本文将为您提供关于使用数组时发生NullPointerException的详细介绍,我们还将为您解释数组 null的相关知识,同时,我们还将为您提供关于android – 为什么使用标准BillingService会发生NullPointerException?、ConcurrentHashMap 产生NullPointerException、java – 在类中访问数组时出现NullPointerException、java-NullPointerException-这怎么可能发生?的实用信息。

本文目录一览:

使用数组时发生NullPointerException(数组 null)

使用数组时发生NullPointerException(数组 null)

我正在尝试为在线Java课程创建程序。该程序包括Employee类和Name类。我必须创建多个Employee对象,并提示用户输入员工的姓名。我将所有Employee对象存储在一个employee数组中。

这是代码:

    //Creates employee array with the number of array elements being however many              //employees there are:    Employee employee[] = new Employee [ numEmp ];    for( int j = 0; j < numEmp; j++ )    {        System.out.println( "Please enter the first name of employee number "                + ( j + 1 ) );        Scanner input2 = new Scanner( System.in );        String nameF = input2.nextLine();        //This should set the employee object at employee array element "j" to the                  //String nameF        employee[ j ].setFirstName( nameF );

问题是编译器在运行程序时说最后一行是NullPointerException。我不确定自己在做什么错。有什么建议?

谢谢!-西恩

答案1

小编典典

您创建了一个大小为的新数组numEmp,但是每个元素的默认值为null。这意味着该数组最初包含numEmp空引用。您需要先new实例化每个Employee对象,然后才能对其调用方法。

您可以在创建数组后立即执行以下操作:

Employee employee[] = new Employee [ numEmp ];for( int j = 0; j < numEmp; j++ ){    employee[j] = new Employee();}

或者,可以在您首先需要使用该对象之前,在现有循环中执行此操作:

employee[j] = new Employee();employee[j].setFirstName(nameF);

android – 为什么使用标准BillingService会发生NullPointerException?

android – 为什么使用标准BillingService会发生NullPointerException?

我在我的应用程序中使用标准BillingService(即从sample application复制而不做更改).
但有时我的应用程序崩溃与logcat中的以下数据:

04-16 10:05:43.556: INFO/ActivityManager(96): Start proc tv.kinobaza.app for service tv.kinobaza.app/tv.kinobaza.billing.BillingService: pid=28748 uid=10081 gids={3003}
04-16 10:05:43.646: DEBUG/AndroidRuntime(28748): Shutting down VM
04-16 10:05:43.656: WARN/dalvikvm(28748): threadid=1: thread exiting with uncaught exception (group=0x400259f8)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748): FATAL EXCEPTION: main
04-16 10:05:43.656: ERROR/AndroidRuntime(28748): java.lang.RuntimeException: Unable to start service tv.kinobaza.billing.BillingService@4632f578 with null: java.lang.NullPointerException
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3282)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at android.app.ActivityThread.access$3600(ActivityThread.java:135)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2211)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at android.os.Looper.loop(Looper.java:144)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at android.app.ActivityThread.main(ActivityThread.java:4937)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at java.lang.reflect.Method.invokeNative(Native Method)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at java.lang.reflect.Method.invoke(Method.java:521)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at dalvik.system.NativeStart.main(Native Method)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748): Caused by: java.lang.NullPointerException
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at tv.kinobaza.billing.BillingService.onStart(UnkNown Source)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at android.app.Service.onStartCommand(Service.java:420)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3267)
04-16 10:05:43.656: ERROR/AndroidRuntime(28748):     ... 10 more
04-16 10:05:43.736: DEBUG/SurfaceFlinger(96): Layer::setBuffers(this=0xb947a8),pid=96,w=1,h=1
04-16 10:05:43.736: DEBUG/SurfaceFlinger(96): Layer::setBuffers(this=0xb947a8),h=1
04-16 10:05:43.766: DEBUG/SurfaceFlinger(96): Layer::requestBuffer(this=0xb947a8),index=0,w=480,h=418 success
04-16 10:05:43.986: DEBUG/dalvikvm(28721): GC_FOR_MALLOC freed 9604 objects / 1369120 bytes in 102ms

这是相关的代码:

/**
 * We don't support binding to this service,only starting the service.
 */
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onStart(Intent intent,int startId) {
    handleCommand(intent,startId);
}

这有什么不对?

我注意到了 – 当设备在夜间睡觉时,一旦我开始使用它,它会在约5分钟内崩溃.

并且,以下是更多详细信息:BillingService从我的应用程序的“首选项”屏幕开始.这里是Preferences类的代码:

@Override
protected void onDestroy() {
mBillingService.unbind();
    super.onDestroy();
}

UPD.也许,我应该在Main活动中启动此服务/解除绑定?

这是我的proguard.cfg:

-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.broadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-keep class com.android.vending.billing.**

-keepclasseswithmembernames class * {
    native java.lang.String);
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-libraryjars /lib/libGoogleAnalytics.jar
-libraryjars /lib/signpost-commonshttp4-1.2.1.1.jar
-libraryjars /lib/signpost-core-1.2.1.1.jar
-dontwarn org.apache.commons.codec.binary.Base64
最佳答案
所以你在proguard之后得到这个NPE而不是事先.

你必须混淆一些你不应该喜欢扩展应用程序/活动/服务的类

你不应该混淆这些类:

http://proguard.sourceforge.net/index.html#/manual/examples.html(转到例7)

ConcurrentHashMap 产生NullPointerException

ConcurrentHashMap 产生NullPointerException

今天测试在发给我一段报错日志后,根据日志定位到从ConcurrentHashMap 的缓存中get的时候,ConcurrentHashMap的底层抛出了空指针,当时感觉很奇怪为什么在get的时候产生空指针了呢?

模拟代码:

ConcurrentHashMap  concurrentHashMap = new ConcurrentHashMap();

........................................................

concurrentHashMap.get(传入的参数);

这个地方出现空指针,难道是传入的null 所以出现了空指针了,事实证明确实传入了null,但是我记得hashmap 是可以传入null 的呀? 为什么ConcurrentHashMap 却不行呢?

相应的去验证了一下,remove  方法发现也不能传入null 进去。

一、异常分析

FATAL EXCEPTION: main
java.lang.NullPointerException
    at java.util.concurrent.ConcurrentHashMap.remove(ConcurrentHashMap.java:921)

本以为是并发异常,后发现不对,因为ConcurrentHashMap已经使用继承自ReentrantLock的Segment,保证了线程安全,Java如果有这么大的bug肯定早修复了。看了下源码

发现自己大意了,在获取hashCode时NPE(hashMap不会,因为它会对null key做一次处理)。ConcurrentHashMap不接受null key和null value这个常识一时疏忽了,调用的地方确实有可能传入null。这样在remove前进行null判断即可解决。

在问题解决后,想到hashMap和linkedhashMap都允许null key和null value,treeMap不允许null key,但允许null value,而ConcurrentHashMap既不允许null key也不允许null value,why?

二、not allow null key and value
stackoverflow并结合了源码分析了一下
(1) treeMap不允许null key是因为compare会导致NPE, 可通过以下代码实现null key支持

SortedMap<Integer, Integer> map = new TreeMap<Integer, Integer>(new Comparator<Integer>() {
 
                                    @Override
                                    public int compare(Integer arg0, Integer arg1) {
                                        if (arg0 == null) {
                                            if (arg1 == null) return 0;
                                            return -1;
                                        }
                                        if (arg1 == null) return 1;
                                        return arg0.compareTo(arg1);
                                    }
                                });

(2) ConcurrentHashMap不允许null key和null value,是因为ConcurrentHashMap的锁机制
对于get(Object key)如果返回null,ConcurrentHashMap没办法判断是key不存在还是value就是null。有人得问了那么hashmap呢, 为什么可以,hashmap我们可以通过下面代码实现判断

Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());
String key = "aa", value;
synchronized (map) {
    if (map.containsKey(key)) {
        value = map.get(key);
    } else {
        throw new Exception("key is not exist");
    }
}

使用Collections.synchronizedMap对hashmap加锁,Collections.synchronizedMap的锁是同步锁,就是对象本身,所以synchronized (map)与Collections.synchronizedMap内锁统一。而ConcurrentHashMap的并发控制是利用分离锁实现的(16个重入锁),在外部无法获得锁,自己也没有提供函数进行判断,所以无奈了。

那么有没有办法既保证map的并发安全同时又允许null key和null value呢,当然了,两种方式
第一种实际上面已经展现了,通过Collections.synchronizedMap对hashmap加锁即可。synchronizedMap保证了线程安全,hashmap又允许null key和null value。

不过Collections.synchronizedMap的并发性能自然比不上ConcurrentHashMap的分桶锁机制,如果对性能要求较高
理论上也可以重写ConcurrentHashMap添加一个函数支持上面代码段的并发,但这个要求对ConcurrentHashMap的分离锁相当熟悉

最后:

关于为什么这么设计:

https://laiqitech.com/125/

关于null的一些小知识:

http://www.importnew.com/14229.html

java – 在类中访问数组时出现NullPointerException

java – 在类中访问数组时出现NullPointerException

我是这个论坛和Java的新手.下面的代码编译但是当我尝试为变量输入一个值时,我得到NullPointerException.怎么了?

class output_harm
{
    public int[] timestamp;
    public int[] state;

    public output_harm(){
        timestamp = new int[8];
        state = new int[8];
    }
}

output_harm[][] outputs =  new output_harm[7][6];   

outputs[0][0].state[0] = 0; //java.lang.NullPointerException

解决方法:

问题
output_harm [] [] outputs = new output_harm [7] [6];

这只是初始化一个数组.
当你调用构造函数output_harm()时,它只会进行初始化.
state = new int [8];这里的状态在构造函数中初始化并导致NullPointerException.

解:
首先,您需要为每个output_harm初始化一个对象(如果您需要初始化整个数组)

output_harm[][] outputs =  new output_harm[7][6];   
    for(int i=0;i<7;i++){
        for(int j=0;j<6;j++){
            outputs[i][j] = new output_harm();
        }
    }

    outputs[0][0].state[0] = 1;

java-NullPointerException-这怎么可能发生?

java-NullPointerException-这怎么可能发生?

得到的代码如下所示:

// This is com.n.common.Networking.downloadBmp( ) function
// ...
byte[] data = inputStreamToByteArray(new PatchedInputStream(connectJava(url)));

// if the data is null in this moment - return;
if (data == null)      // <--- line 185
    return null;
// ...

并得到了这样的异常:

ERROR/AndroidRuntime(4526): Uncaught handler: thread pool-1-thread-2 exiting due to uncaught exception
ERROR/AndroidRuntime(4526): java.lang.NullPointerException
ERROR/AndroidRuntime(4526):     at com.n.common.Networking.downloadBmp(Networking.java:185)
ERROR/AndroidRuntime(4526):     at com.n.common.AsyncNetworking$3.run(AsyncNetworking.java:203)
ERROR/AndroidRuntime(4526):     at java.lang.Thread.run(Thread.java:1060)
ERROR/AndroidRuntime(4526):     at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
ERROR/AndroidRuntime(4526):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
ERROR/AndroidRuntime(4526):     at java.lang.Thread.run(Thread.java:1060)

那怎么可能?

编辑:这很可能是由于使用了Eclipse的“组织导入”功能,该功能更改了行号-并将较新的代码版本与已部署的旧版本进行比较.谢谢大家的帮助.

解决方法:

应该是部署问题或与保存文件并具有多个版本有关的问题.引发Exception的代码必须与您发布的内容不同的第185行.

尝试清理/重新编译/(重新部署),看看行号是否更改

关于使用数组时发生NullPointerException数组 null的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于android – 为什么使用标准BillingService会发生NullPointerException?、ConcurrentHashMap 产生NullPointerException、java – 在类中访问数组时出现NullPointerException、java-NullPointerException-这怎么可能发生?的相关信息,请在本站寻找。

本文标签: