【问题标题】:Removing an element of a class that has an element that is list of another class删除一个类的元素,该元素的元素是另一个类的列表
【发布时间】:2018-08-30 00:35:42
【问题描述】:

我有这两个类:

public class Table {
    String tableName;
    private List <Column> columns;
}

public class Column {
    String columnName;
}

我创建了两个Table 类列表:

List<Table> table1 = new ArrayList<Table>();
List<Table> table2 = new ArrayList<Table>()

并从 Oracle DB 中获取此列表的值。

table1 = tableDao.ListTabColumns();
table2 = tableDao.ListTabColumns();

我尝试了removeAll,但没有成功。

table1.removeAll(table2);

而且...Set&lt;Table&gt; 和 removeAll 也不起作用。

Set<Table> t1 = new HashSet<Table>(table1);
Set<Table> t2 = new HashSet<Table>(table2);
t1.removeAll(t2); 

我尝试对table2 中table1 的每个元素使用contains,但什么也没有。

唯一可行的方法是 List 的每个元素的内部循环以及 List 的每个元素的内部循环之后。

for(Table t : table1) {
    for(Table x : table2) {
        System.out.println(t.getTableName());
        for(Column c : x.getColumn()) {
            for (Column d : t.getColumn()) {
                // Something to display if not contain any equals.
            }
        }
    }
}

但我认为这不是最好的方法。 有人可以帮助我吗? 提前致谢!

【问题讨论】:

  • 您是否覆盖了Column 对象中的equals 和hashCode 函数?

标签: java list class removeall


【解决方案1】:

我做了这个覆盖并且工作正常:

@Override
    public boolean equals(Object obj) {
    if (obj == null)
         return false;
    if (!(obj instanceof Column))
         return false;
    Column c = (Column) obj;
    return this.columnName == null ? false : this.columnName.equals(c.columnName);
    }

@Override
    public int hashCode() {
        return this.columnName == null ? 0 : this.columnName.hashCode();
    }

非常感谢,Michał Piątkowski!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多