【问题标题】:Getting nullpointerexception when trying to add same String to ArrayList Class [duplicate]尝试将相同的字符串添加到 ArrayList 类时出现 nullpointerexception [重复]
【发布时间】:2022-01-19 21:55:05
【问题描述】:

当我尝试将相同的字符串两次添加到 ArrayList 时,我得到一个 NullPointerException 但不知道为什么。

import java.util.ArrayList;

public class BankOne {

    private String name;
    private ArrayList<BranchOne> branches;

    public BankOne(String name) {
        this.name = name;
        this.branches = new ArrayList<BranchOne>();
    }

    public boolean addBranch(String branchName) {
        if(findBranch(branchName) == null) { //Checking to see if branch exists already.
            this.branches.add(findBranch(branchName));
            System.out.println(branchName + " has been added to the list");
            return true;
        } else {
            return false;
        }
    }

    private BranchOne findBranch(String branchName) {
        for(int counterOne = 0; counterOne < this.branches.size(); counterOne++) {
            BranchOne branch = branches.get(counterOne);
            if (branch.getName().equals(branchName)) {
                System.out.println(branch.getName() + " exists");
                return branch;
            }
        }
        return null;
    }

public class BranchOne {

    private String name;
    private ArrayList<CustomerOne> customers;

    public BranchOne(String name) {
        this.name = name;
        this.customers = new ArrayList<CustomerOne>();
    }

    public String getName() {
        return name;
    }

    public ArrayList<CustomerOne> getCustomers() {
        return customers;
    }

}

【问题讨论】:

  • 您应该包含一个堆栈跟踪,它会告诉您发生 NPE 的确切行,并指出代码示例中的行。
  • 同时分享主代码,看看你在运行代码时使用了哪些值
  • this.branches.add(findBranch(branchName)) — 您将 null 放入列表中。当您假设列表中的元素是对象时,这将导致 NPE。

标签: java arraylist nullpointerexception


【解决方案1】:

这部分:

if(findBranch(branchName) == null) { //Checking to see if branch exists already.
            this.branches.add(findBranch(branchName));

必须将null 添加到您的branches 列表中

从那里 NPE 是相当明显的。我想你的意思是this.branches.add(branchName) 或诸如此类的东西。

【讨论】:

    【解决方案2】:

    如果findBranch(branchName) 给出null,则将其添加到列表中,即null,因此下一次调用branch.getName() 会引发错误


    当没有给定名称的项目时,实例化并添加BranchOne

    public boolean addBranch(String branchName) {
        if (findBranch(branchName) == null) {
            this.branches.add(new BranchOne(branchName));
            return true;
        } else {
            return false;
        }
    }
    

    方法findBranch可以用for-each循环来简化

    private BranchOne findBranch(String branchName) {
        for (BranchOne branch : this.branches) {
            if (branch.getName().equals(branchName)) {
                return branch;
            }
        }
        return null;
    }
    

    【讨论】:

    • 啊哈,非常感谢大家!
    猜你喜欢
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 2023-03-22
    • 1970-01-01
    • 2013-06-04
    • 2018-01-20
    • 1970-01-01
    相关资源
    最近更新 更多