【问题标题】:Java Collection framework, Arraylist working with objectsJava Collection 框架,Arraylist 处理对象
【发布时间】:2020-08-30 17:04:29
【问题描述】:

这是开始的分支类:

package com.sherzod;

import java.util.ArrayList;

public class Branch {
    private String branchName;
    private ArrayList<Customer> customer;

    public Branch(String branchName) {
        this.branchName = branchName;
        this.customer = new ArrayList<>();
    }

    public String getBranchName() {
        return branchName;
    }

    public ArrayList<Customer> getCustomer() {
        return customer;
    }

    **public Customer findCustomer(String name){
        for (int i=0; i<this.customer.size(); i++){
            Customer checkedCustomer = this.customer.get(i);
            if(checkedCustomer.equals(name)){
                return checkedCustomer;
            }
        }
        return null;
    }**
}

这里开始客户类:

package com.sherzod;

import java.util.ArrayList;

public class Customer {
    private String customerName;
    private ArrayList<Double> transactions;

    public Customer(String customerName) {
        this.customerName = customerName;
        this.transactions = new ArrayList<>();
    }

    public String getCustomerName() {
        return customerName;
    }

    public ArrayList<Double> getTransactions() {
        return transactions;
    }

    public void addTransaction(double amount){
        transactions.add(amount);
    }
}

问题是我们如何创建一个返回(作为布尔值)类型“客户”对象的方法? 即使我没有从 Branches 扩展 Customer 类,代码仍然有效,没有错误。 所以意味着 Customer 与 Branch 类有关系,因为我在 Branch 类中初始化 Customer Arraylist?我从 8 个月开始学习 java,现在很困惑..

【问题讨论】:

  • 问题是我们如何创建一个返回(作为布尔值)类型“客户”对象的方法? - 你能改写你想问的问题吗?真的很难理解你的问题是什么。
  • 我的意思是,通常如果我们想要返回一些东西,我们会这样:“public (int, double, String etc.,) methodName(){}”对吗?但是在 Branch 类中,我正在编写一个类似的方法:“public Customer findCustomer()”并且 findCustomer 返回一个对象?这部分我不明白
  • ..和?那你的问题是什么?你想让你的方法返回boolean吗?或者..?请提出问题。
  • 你能解释一下我们从哪里得到这个“findCustomer”方法吗?什么是返回数据类型?
  • public Customer findCustomer(String name) 的返回类型是Customer,您显然可以看到这一点。我不知道您从哪里获得此方法

标签: java arraylist collections


【解决方案1】:

对于包中的 java 类,您不需要导入同一个包中的其他公共类。 即 Customer 类不需要导入到 Branch 类中(因为两者都是 com.sherzod 的一部分),不像 ArrayListjava.util 包的一部分。

为:

even if I didn't extend Customer class from Branches still code works, no errors. 

继承是一个不同的主题。关系 b/w Branches 和 Customer 类是它们在同一个包中,它们不需要有父子关系

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    相关资源
    最近更新 更多