【问题标题】:How to put a object in a linked list?如何将对象放入链表中?
【发布时间】:2016-03-12 22:20:45
【问题描述】:

我正在尝试制作银行记录并尝试使用链表。我做了我的银行类,我试图把它作为一个对象放在我的主类中并打印输出。所以如果我输入詹姆斯作为名字,黑色作为我的姓氏,200 作为余额。它应该打印输出:FirstName:James,Lastname:Black,Balance:200。如果我添加另一个first,last,balance。它应该用旧记录打印新记录。

Example:
First name      Lastname     Balance
James            Shown        4000
Kyle             Waffle       2000

银行类:

public class Customer2 {
    String Firstname,Lastname;
    public int balance, amount;
    int total=0;
    int total2=0;
    Scanner input = new Scanner(System.in);

public Customer2(String n, String l, int b){
    Firstname=n;
    Lastname=l;
    balance=b;
}
    public void withdraw(int amount){
        total=balance-amount;
        balance=total;

    }
    public void deposit(int amount){
        total=balance+amount;
        balance=total;
    }
    public void display(){
        System.out.println("FirstName: "+" Lastname: "+" Balance");
        System.out.println(Firstname+"         "+Lastname+"      " +balance);
    }

主类:

LinkedList<Customer2> list = new LinkedList<Customer2>();
list.add("Bob");
list.getfirst("Lastname");

【问题讨论】:

  • 你有什么问题?
  • 如何将我的银行类作为对象放入我的链表中。
  • 您需要创建一个新的 customer2 对象并将其添加到您的链接列表中

标签: java class linked-list


【解决方案1】:

您应该创建一个新的 customer2 对象,然后将其添加到您的链接列表中

看起来像这样: 主类:

Customer2 customer = new Customer2("Bob", "Doe", 1000);
list.add(customer);

Bob 现在将被添加到链表中。

如果你想从链表中检索 bob,你可以遍历链表直到找到 bob,然后在该对象上调用 display。

或者您可以使用 getFirst(如果 bob 是列表中的第一个)

看起来像这样:

list.getFirst().display();

链表类中还有其他方法可以用来添加或获取,如果你知道位置的话。这是一个链接:http://www.tutorialspoint.com/java/java_linkedlist_class.htm

我也认为这就是你想要的 display() 方法:

public void display(){
System.out.println("First Name: " + firstName + ", Last Name: " + lastName + ", Balance: " + balance);

您还应该使用小写字母来开始变量名称,因为它是一个很好的命名约定。名字变成名字。

【讨论】:

  • 谢谢,这很有意义。我遇到的问题是如果我将另一个人添加到列表中并打印它。它不会像应有的那样跳过一行。
【解决方案2】:

如果你想将元素放入LinkedList&lt;Customer2&gt; list,你需要使用方法list.add(customer),其中customer是来自类Customer2的对象。

【讨论】:

  • 你能举个例子吗?
【解决方案3】:
LinkedList<Customer2> list = new LinkedList<Customer2>();
Customer2 c = new Customer2("firstName","lastName",1000);
list.add(c);
System.out.println(list);

覆盖 Customer2 类中的 toString():

 @Override
   public String toString(){
      return "FirstName: "+fristName+",lastName: "+lastName,+"balance" +balance;
   }

//toString()
//returns string for the object

要打印列表中的所有对象,每个 Customer2 对象都在一个新行中

for(Customer2 c : list){
   System.out.println(c);
}

【讨论】:

  • 感谢您的帮助
  • 所以如果我将另一个人添加到列表中。它不会跳到新行
猜你喜欢
  • 2014-10-15
  • 1970-01-01
  • 2022-07-06
  • 2015-12-16
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
相关资源
最近更新 更多