如何在另一个列表对象中添加对象

时间:2017-03-30 22:58:15

标签: java list

我有一个对象类A,以及一个B类的列表对象

A a = a.findById(aId);
List<B> b = b.findById(bId);

班级BA班级

public class B {
   private int id;
   private A a;
   ...getters setters
}

是否可以在对象列表a中添加对象b

当我尝试在对象列表中添加a时出现错误。 b.add(a);这告诉我将对象a更改为B a...

如何在列表对象a中添加对象b

3 个答案:

答案 0 :(得分:0)

如果将对象a包装在对象B中,则可以添加它。否则,由于类型不匹配,您将无法将a类型的对象A添加到List<B>B个对象:您正在尝试添加类型为{的对象{1}}到Java中不允许的A个对象列表。

答案 1 :(得分:0)

  

是否可以在对象列表a中添加对象b

简单地说,不,因为它们不是同一类型。

  

如何在列表对象b中添加对象a?

为了将类A和类B的实例添加到一个集合中,您可以采用的一种方法是创建一个类A和类{{ 1}}实现。

示例:

B

然后让类实现public interface ISomeInterface { // define some methods in which both class `A` and `B` share } 接口:

ISomeInterface

然后你可以这样做:

public class A implements ISomeInterface {

}

public class B implements ISomeInterface {
    private int id;
    private A a;
}

或者根本不需要创建接口:

List<ISomeInterface> b = new ArrayList<>();
b.add(new A());
b.add(new B());
// note you can only call methods through which the interface defines
// another solution is to cast the types, that way you can invoke the methods that belong to each type
// make use of instanceof keyword to prevent exception

答案 2 :(得分:0)

将A添加到B的语法首先得到B,然后将A添加到B,例如

A a = new A();
B b = new B();

b.add(A);

如果您希望将两者都添加到同一个List<>,那么他们需要实现相同或继承自同一个类,例如interface IAB

List<IAB> list = new ArrayList<>();

list.add(new A());
list.add(new B());

鉴于

public interface IAB{}
public class A implements IAB{}
public class B implements IAB();

请注意,在这种情况下,您只能调用接口上可用的方法,除非您将其强制转换为类(但如果混合使用可能很复杂的A和B)