【问题标题】:How to add customer details within a ArrayList?如何在 ArrayList 中添加客户详细信息?
【发布时间】:2013-01-21 18:43:54
【问题描述】:

我正在尝试创建客户。我正在尝试将每个用户输入添加到 arrayList 中,并使其在最后输出。但是,我的输出给了我一些内存位置。有人可以对此有所了解吗?

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter First Name: ");
    String firstName = input.nextLine();
    System.out.println("Enter Last Name: ");
    String lastName = input.nextLine();
    System.out.println("Enter Home Address: ");
    String homeAddress = input.nextLine();

    Customer cus = new Customer(firstName, lastName, homeAddress);

    System.out.println("\nWelcome: ");
    System.out.print(cus.getFirstName() + cus.getLastName());
    System.out.println("\n Your Shipping Address: ");
    System.out.print(cus.getHomeShippingAddress());

    List<Customer> customer = new ArrayList<Customer>();

    customer.add(cus);

    // Output the list contents
    printList(customer);

}

public static void printList(List<Customer> list) {

    System.out.println("Customers: ");

    for (Customer customer : list) {
        System.out.printf("%s", customer);
    }
    System.out.println();
}

}

【问题讨论】:

  • 您应该重写toString() 方法以获得有意义的输出。
  • 我喜欢toString答案风暴前的超现实平静。
  • 评论解决了这个问题。;) 字符串覆盖。
  • 评论解决了大多数问题

标签: java list arraylist


【解决方案1】:

覆盖Customer 对象的toString 方法。

当前是默认实现。

以防万一您想知道@5c694a18 的含义:它是您的Customer 对象的哈希码的无符号十六进制表示。

【讨论】:

    【解决方案2】:

    您正在尝试打印一个对象,因此它转到其toString() 方法。您可能希望通过覆盖从Object 继承的方法来实现自己的toString() 方法。

    类似:

    @Override 
    public String toString() {
        StringBuilder result = new StringBuilder();
        //build your string here. 
        //Perhaps by appending the customer's first and last name?
        return result.toString();
    }
    

    您目前看到的,继承自 Object,是这样的:

    getClass().getName() + '@' + Integer.toHexString(hashCode())

    【讨论】:

      【解决方案3】:

      由于您没有在 Customer 类中覆盖 toString,因此会调用 Objects 的 toString,这将返回 NameOfTheClass +"@" +SomeHexNumber.

       return getClass().getName() + "@" + Integer.toHexString(hashCode());
      

      Customer class 中覆盖toString() method,以便打印适当的数据。 如下所示:

      public String toString() {
      return this.firstName+" " + this.lastName ;
      }
      

      【讨论】:

        【解决方案4】:

        Customer 是一个对象,你需要重写 toString() 方法来输出你想要的关于该对象的值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-02-08
          • 1970-01-01
          • 1970-01-01
          • 2017-10-02
          • 1970-01-01
          • 1970-01-01
          • 2017-08-04
          相关资源
          最近更新 更多