【发布时间】:2019-06-20 00:02:47
【问题描述】:
我学Java,现在在ArrayList,我写了一些关于银行的方法,当我想在特定的分行添加新客户时,位置总是返回0。这是我的方法的源代码正在谈论:
-
Main类中的实例:
public static Scanner scanner = new Scanner(System.in); public static Bank newBank = new Bank("BMCE"); -
主类(添加新客户的静态方法):
public static void addNewCostumer(){ System.out.println("Choose a branch :"); String branchChoosed = scanner.nextLine(); Branches branches = newBank.queryBranch(branchChoosed); if(branches == null){ System.out.println("There are a problem, or you are entered a wrong name of branch"); } else{ System.out.println("Enter the name costumer :"); String nameOfCostumer = scanner.nextLine(); System.out.println("Enter the transaction number :"); double transactions = scanner.nextDouble(); scanner.nextLine(); if(newBank.addNewCostumer(branches,nameOfCostumer,transactions)){ System.out.println("The costumer was created in branch name :"+branches.getNameOfBranch()); }else{ System.out.println("Sorry you dindn't create a costumer in "+branches.getNameOfBranch()+" Try again please :)"); } } -
Bank 类中的实例:
private String name; private ArrayList<Branches> branchesArrayList = new ArrayList<>(); -
银行类:
public boolean addNewCostumer(Branches nameOfExistingBranch,String nameOfNewCostumer,double newTransaction){ int position = findBranch(nameOfExistingBranch); if(position<0){ System.out.println("There is not branch with this name"); return false; } else{ if(this.branchesArrayList.get(position).findCostumer(nameOfNewCostumer)>=0){ System.out.println("You have already an existing costumer with that name"); return false; } else{ this.branchesArrayList.get(position).addNewCostumer(nameOfNewCostumer,newTransaction); return true; } } } -
寻找分支的方法:
public int findBranch(Branches branches){ int position = this.branchesArrayList.indexOf(branches); if(position>=0){ return position; } else return -1; } -
输入:
0-Mdiq
1-卡萨
2-拉巴特
当我向 Rabat 或 Casa Branch 添加新客户时,客户总是在 Mdiq(位置 0)中记录。
【问题讨论】:
-
BTW public int indexOf(Object o) 返回此列表中指定元素第一次出现的索引,如果此列表不包含该元素,则返回 -1。更正式地说,返回满足 (o==null ? get(i)==null : o.equals(get(i))) 的最低索引 i,如果没有这样的索引,则返回 -1。 如何你实现了吗
equals -
我的期望是他们没有覆盖
equals。但是,这意味着indexOf会进行==的检查,更加严格 -
@JClassic 同意你的说法,但我指望的是一个执行不力的
equals -
您向我们展示了很多我们不需要的代码,而没有发布我们确实需要查看的代码。正如
ArrayList::indexOf的Javadoc 所解释的,您通过Objects.equals覆盖Object::equals是列表搜索对象的机制。您的equals方法可能存在缺陷,但您没有显示它,所以我们不确定。 -
在发布之前,请务必彻底搜索 Stack Overflow。比较对象是否相等已经被讨论过无数次了。
标签: java arraylist position indexof autoboxing