我是初学Java程序员,我试图在一个链表中添加一个名为Person的选定对象到另一个名为Boat的实例类中包含的链表。我能够选择我想要的两个对象,但我不知道如何将所选人员添加到所选Boat对象的链接列表中。我已经包含了Person和Boat类的详细信息以提供帮助。
我已将代码删除至最基本的问题,以传达问题,如果更多的程序会有所帮助请告诉我。任何帮助表示赞赏。如果我的问题不明确,请告诉我,我会尝试重新解释这个问题。
以下是我目前使用的两种方法,以及存储船只的列表。我用'// !!'标记了关键区域
public class Base implements Serializable
{ private LinkedList<Boat> boats = new LinkedList<Boat>();
private Clients clients = new Clients();
public Base(){
}
// !! Here is where the boats are created
public void setup()
{ boats.add(new Boat(1, "Ed", 2));
boats.add(new Boat(2, "Fred", 7));
boats.add(new Boat(3, "Freda", 5)); }
public void getBoat(Boat boat) { `// !! Boat has already been selected by another method`
boat.passengers(add(getPassenger(passenger))); `// !! This is where I try to add the Person object into the linked list of the Boat object, this is the line that generates errors.`
}
public Person getPassenger(Person passenger) { `// !! passenger has already been selected by another method`
return passenger;
}
这是船类
import java.io.*;
import java.util.*;
public class Boat implements Serializable
{
private LinkedList<Person> passengers = new LinkedList<Person>();
public Boat()
{
}
}
这是人类
import java.io.*;
import java.text.*;
public class Person implements Serializable
{ private String name;
private int id;
private double cash = 100.00;
private int start = 0;
private int end = 0;
private double charge = 0;
public Person(String name, int id)
{ this.name = name;
this.id = id + 100; }
}
答案 0 :(得分:1)
您可以在班级Boat
中创建一个方法来执行此操作:
public class Boat implements Serializable {
private LinkedList<Person> passengers = new LinkedList<Person>();
public Boat() { }
public void addPassenger(Person p) {
this.passengers.add(p);
}
}
然后,您可以将Person
对象传递给addPassenger()
,从而将乘客添加到特定的船只中。例如:
Boat boat = new Boat();
boat.addPassenger(new Person("Bob", 1));
不要在getter方法中返回乘客列表。这将打破封装,因为其他类可以修改船的乘客名单甚至清理它。
您的代码中还有一些问题。例如:
public Person getPassenger(Person passenger) {
return passenger;
}
此方法接收一个对象并返回该对象。它没有别的。你不需要它。
您的getBoat()
方法收到Boat
作为参数,但在其中您尝试访问Passenger
对象。这位乘客是从哪里来的?
public void getBoat(Boat boat) {
boat.passengers(add(getPassenger(passenger)));
}
似乎这个方法应该是这样的:
public void addPassengerToBoat(Boat boat, Passenger passenger) {
boat.addPassenger(passenger);
}
答案 1 :(得分:0)
//由于Boat类中的乘客处于私人范围内。你不能这样访问。如果你在Boat类中有一个getter()和setter()方法用于传递
public void getBoat(Boat boat) { `// !! Boat has already been selected by another method`
boat.getPassengers().add(getPassenger(passenger)));
}
在船级,
public LinkedList<Person> getPassengers(){
return this.passengers;
}