天道酬勤,学无止境

How does ListUtils.subtract() work?

I am trying to subtract the values of one list from another with the ListUtils.subtract(1,2) however I noticed that the subtraction never occurs so I keep getting all the elements in 1 returned. I thought this might be indicative of an equality issue but my hashcode and equals method are fine.(I think)

   @Override
    public boolean equals(Object o) {
        if(!(o instanceof Car))
            return false;

        Car ct = (Car) o;

        return this.getManufacturer().equals(ct.getManufacturer())
                && this.getImmat().equals(ct.getImmat())
                && this.getModel().equals(ct.getModel());
    }

@Override
public int hashCode() {
    int hash = 5;
    hash = 71 * hash + (this.model != null ? this.model.hashCode() : 0);
    hash = 71 * hash + (this.immat != null ? this.immat.hashCode() : 0);
    hash = 71 * hash + (this.manufacturer != null ? this.manufacturer.hashCode() : 0);
    return hash;
}

The code that does the subtraction:

            List <Car> affected = new LinkedList<Car>();

            for(Driver c : tmp)
                affected.add(c.getCar());

           List <Car> allcars = carDAO.findAllCars("order by model");//returns every car

            List<Car> cars = ListUtils.subtract(allcars, affected );


    return cars;

I have inspected both lists and they're fine, I however can't get ListUtils to subtract affected from allcars (returns the allcars set) leading me to think for some reason the equals method could be wrong.

评论

Plain answer (Assuming you mean Apache Commons Collections): According to the source code of ListUtils.subtract(List, List) it uses ArrayList.remove(Object) which in turn uses equals() to determine the items to delete.

To your problem: My guess would be to look into the equals method. Is the one you are providing really called? Are the dependent methods (for Manufacturer etc.) correct?

getManufacturer() returns a Manufacturer, and you haven't overridden .equals and .hashCode there, so two Manufacturer instances with identical fields will not be counted as equal.

This is based on extra context from IRC, so please add that to your question so that it's useful for others. The general rule is that with a test case you would have got an accurate answer sooner.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Java:比较两个字符串数组并删除两个数组中都存在的元素(Java: Comparing two string arrays and removing elements that exist in both arrays)
    问题 这主要是一个性能问题。 我有一个字符串数组AllUids中现有的所有用户的主列表。 我还列出了String数组EndUids中存在的所有已过期用户。 我正在使用Java进行工作,我的目标是从主列表AllUids中删除截止日期数组中存在的所有用户。 我知道PHP有一个叫做array_diff的函数。 我很好奇Java是否具有可以比较两个数组并删除两个相似的元素的东西。 我的目标是这里的性能,这就是为什么我问一个内置函数的原因。 我不想添加任何特殊的程序包。 我考虑过编写一个递归函数,但似乎效率很低。 两个列表中都有成千上万的用户。 为了存在于过期日期列表中,您必须存在于AllUids列表中,直到删除。 例子: String[] AllUids = {"Joe", "Tom", "Dan", "Bill", "Hector", "Ron"}; String[] EndUids = {"Dan", "Hector", "Ron"}; 我正在寻找的功能: String[] ActiveUids = AllUids.RemoveSimilar(EndUids); ActiveUids看起来像这样: {"Joe", "Tom", "Bill"} 谢谢大家,显然我可以提出这样的循环,但是我不确定这样做会有效。 这是每天都会在生产机器上运行的东西。 回答1 Commons
  • Does std::move work with lvalue references? How does std::move work on standard containers?
    #include <vector> struct A { int a[100]; }; void foo (const A& a) { std::vector<A> vA; vA.push_back(std::move(a)); // how does move really happen? } int main () { A a; foo(a); } The above code compiles fine. Now everywhere it's written that move avoids copying. Following are my queries: Does the move really work when one deals with a lvalue [non]-const reference? Even with "rvalue reference", how is the copy avoided when the object is inserted into a standard container like above? e.g. void foo (A&& a) { // suppose we invoke this version std::vector<A> vA; vA.push_back(std::move(a)); // how
  • How does the GCC implementation of modulo (%) work, and why does it not use the div instruction?
    I was trying to work out how to calculate modulo 10 in assembly so i compiled the following c code in gcc to see what it came up with. unsigned int i=999; unsigned int j=i%10; To my surprise I got movl -4(%ebp), %ecx movl $-858993459, %edx movl %ecx, %eax mull %edx shrl $3, %edx movl %edx, %eax sall $2, %eax addl %edx, %eax addl %eax, %eax movl %ecx, %edx subl %eax, %edx movl %edx, %eax movl %eax, -12(%ebp) Where -4(%ebp) or "i" is the input and -12(%ebp) or "j" is the answer. I've tested this and it does work no matter what number you make -4(%ebp). My question is how does this code work and
  • How does operator<< overloading work?
    Given a class: struct employee { string name; string ID; string phone; string department; }; How does the following function work? ostream &operator<<(ostream &s, employee &o) { s << o.name << endl; s << "Emp#: " << o.ID << endl; s << "Dept: " << o.department << endl; s << "Phone: " << o.phone << endl; return s; } cout << e; produces formatted output for a given employee e. Example output: Alex Johnson Emp#: 5719 Dept: Repair Phone: 555-0174 I can't understand how the ostream function works. How does it get the parameter "ostream &s"?How does it overload the "<<" operator and how does the <<
  • How does the mechanism behind the creation of boxed traits work?
    I'm having trouble understanding how values of boxed traits come into existence. Consider the following code: trait Fooer { fn foo(&self); } impl Fooer for i32 { fn foo(&self) { println!("Fooer on i32!"); } } fn main() { let a = Box::new(32); // works, creates a Box<i32> let b = Box::<i32>::new(32); // works, creates a Box<i32> let c = Box::<dyn Fooer>::new(32); // doesn't work let d: Box<dyn Fooer> = Box::new(32); // works, creates a Box<Fooer> let e: Box<dyn Fooer> = Box::<i32>::new(32); // works, creates a Box<Fooer> } Obviously, variant a and b work, trivially. However, variant c does not
  • What does “list comprehension” mean? How does it work and how can I use it?
    I have the following code: [x ** 2 for x in range(10)] When I run it in the Python shell, it returns: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] I've searched and it seems this is called a list comprehension, but how does it work?
  • Spring Security: same SecurityContext-instance in multiple ThreadLocals, how does that work?
    Ive some questions about Spring Security 3.0.5 and the SecurityContext. First of all, Ill try to conclude what I know: SecurityContextHolder stores SecurityContext Between Request, SecurityContext is stored in HttpSession Begin of Request: SecurityContextHolder gets SecurityContext from HttpSession End of Request: SecurityContextHolder puts SecurityContext in HttpSession During the Request, on the server, SecurityContextHolder uses a ThreadLocal. Everywhere in the application (same request), the SecurityContext can be accessed Now my question.... --> Two Requests: the SecurityContext-instance
  • Angular 7 - How does work the HTML5 Fullscreen API ? I've a lot of errors
    I use Angular 7 and I would like have a button for put my app in fullscreen. I use the HTML5 Fullscreen API and I've make 2 functions : openfullscreen() { // Trigger fullscreen console.log('gg'); if (document.documentElement.requestFullscreen) { document.documentElement.requestFullscreen(); } else if (document.documentElement.mozRequestFullScreen) { /* Firefox */ document.documentElement.mozRequestFullScreen(); } else if (document.documentElement.webkitRequestFullscreen) { /* Chrome, Safari and Opera */ document.documentElement.webkitRequestFullscreen(); } else if (document.documentElement
  • How does AngularJS know when variables change? How does AngularJS dirty checking work?
    I was reading some article to understand a little bit more how AngularJS works. One of the terms that I didn't understand is Dirty Checking. What is it exactly? It seems like the Observer pattern but apparently it's better. Can you help me understand this please? EDIT : it can be also useful for people who wants to learn more about that to watch this video from swiip at NgEurope some years ago.
  • How does the Content property work
    Both syntaxes below works. My question is how does WPF know Content is what I specified? <Button> <Button.Content> my button </Button.Content> </Button> <Button> my button <!--how does wpf know this is the content--> </Button> similarly, how does wpf know I'm now adding ListBoxItems <ListBox> <!--ListBox.Items--> <ListBoxItem Content="item 1" /> <!--XAML automatically knows I'm specifying items--> item 2 <ListBoxItem Content="item 3" /> <!--/ListBox.Items--> </ListBox> So in ContentControl, the default property is Content, and with ItemsControl, the default is Items, and with TextBox, the
  • 内容属性如何工作(How does the Content property work)
    问题 下面的两种语法都有效。 我的问题是 WPF 如何知道内容是我指定的内容? <Button> <Button.Content> my button </Button.Content> </Button> <Button> my button <!--how does wpf know this is the content--> </Button> 同样,wpf 怎么知道我现在正在添加 ListBoxItems <ListBox> <!--ListBox.Items--> <ListBoxItem Content="item 1" /> <!--XAML automatically knows I'm specifying items--> item 2 <ListBoxItem Content="item 3" /> <!--/ListBox.Items--> </ListBox> 所以在ContentControl中,默认属性是Content,对于ItemsControl,默认是Items,对于TextBox,默认是TextBox。 这个“默认”是如何工作的? 创建自定义控件时如何创建此“默认属性”? 回答1 ContentPropertyAttribute 告诉 xaml 解析器将哪个属性用于直接内容。 Button继承自的ContentControl标记有属性
  • How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?
    I was working on my Spring boot app project and noticed that, sometimes there is a connection time out error to my Database on another server(SQL Server). This happens specially when I try to do some script migration with FlyWay but it works after several tries. Then I noticed that I didn't specify spring.jpa.hibernate.ddl-auto in my properties file. I did some research and found that it is recommended to add spring.jpa.hibernate.ddl-auto= create-drop in development. And change it to: spring.jpa.hibernate.ddl-auto= none in production. But I didn't actually understand how does it really work
  • Why does a pandas Series of DataFrame mean fail, but sum does not, and how to make it work
    There may be a smarter way to do this in Python Pandas, but the following example should, but doesn't work: import pandas as pd import numpy as np df1 = pd.DataFrame([[1, 0], [1, 2], [2, 0]], columns=['a', 'b']) df2 = df1.copy() df3 = df1.copy() idx = pd.date_range("2010-01-01", freq='H', periods=3) s = pd.Series([df1, df2, df3], index=idx) # This causes an error s.mean() I won't post the whole traceback, but the main error message is interesting: TypeError: Could not convert melt T_s 0 6 12 1 0 6 2 6 10 to numeric It looks like the dataframe was successfully summed, but not divided by the
  • c# 如何处理 async void(How does c# handle async void)
    问题 我通常对网络服务器进行编程,起初我认为必须有连续的方法链返回任务,因此堆栈中的内容可能会询问数据库是否已完成。 最近我看到 wpf 代码,它做这样的事情: public async void Execute(object parameter) { await ExecuteAsync(parameter); } 在事件处理程序中调用。 UI 似乎是响应式的,所以我想它确实有效。 它是如何工作的? 这如何转化为aspnet? 回答1 我在我的异步编程最佳实践文章中解释了async void方法的工作原理 - 以及为什么应该避免它们。 async void具有与async Task相同的语义,除了例外。 async void方法将在方法开始时捕获当前SynchronizationContext ,并且该方法的任何异常都将被捕获并直接在该捕获的上下文上引发。 在最常见的场景中,这会导致应用程序级异常,通常是崩溃。 有些人称async void方法为“即发即弃”,但由于它们的特殊行为,我更喜欢“即发即弃”。 :) “避免异步无效”是一般准则,但有一个值得注意的例外:事件处理程序(或逻辑上属于事件处理程序的项目,例如ICommand.Execute实现)。 它是如何工作的? 这如何转化为aspnet? 它就像任何其他async方法一样工作。 主要的平台差异是 UI
  • mysql mha 工作原理_MHA高可用架构工作原理?老男孩MySQL数据库学习
    主库宕机处理过程 1. 监控节点 (通过配置文件获取所有节点信息) 系统,网络,SSH连接性 主从状态,重点是主库 2. 选主 (1) 如果判断从库(position或者GTID),数据有差异,最接近于Master的slave,成为备选主 (2) 如果判断从库(position或者GTID),数据一致,按照配置文件顺序,选主. (3) 如果设定有权重(candidate_master=1),按照权重强制指定备选主. 1. 默认情况下如果一个slave落后master 100M的relay logs的话,即使有权重,也会失效. 2. 如果check_repl_delay=0的化,即使落后很多日志,也强制选择其为备选主 3. 数据补偿 (1) 当SSH能连接,从库对比主库GTID 或者position号,立即将二进制日志保存至各个从节点并且应用(save_binary_logs ) (2) 当SSH不能连接, 对比从库之间的relaylog的差异(apply_diff_relay_logs) 4. Failover 将备选主进行身份切换,对外提供服务 其余从库和新主库确认新的主从关系 5. 应用透明(VIP) 6. 故障切换通知(send_reprt) 7. 二次数据补偿(binlog_server) 想要众多的IT工作者中脱颖而出,就需要拥有高深的技术,学习增值是必不可少的。学习之路
  • How does Java store Strings and how does substring work internally? [closed]
    It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 8 years ago. class StringTesting { public static void main(String args[]) { String str = "abcd"; String str1 = new String("abcd"); String str2 = str.substring(0,2); String str3 = str.substring(0,2); String str4 = str.substring(0,str.length()); String str5 = str1.substring(0,2); String str6 = str1.substring(0,2); String str7 =
  • How does data binding work in AngularJS?
    How does data binding work in the AngularJS framework? I haven't found technical details on their site. It's more or less clear how it works when data is propagated from view to model. But how does AngularJS track changes of model properties without setters and getters? I found that there are JavaScript watchers that may do this work. But they are not supported in Internet Explorer 6 and Internet Explorer 7. So how does AngularJS know that I changed for example the following and reflected this change on a view? myobject.myproperty="new value";
  • How does module loading work in CPython?
    How does module loading work in CPython under the hood? Especially, how does the dynamic loading of extensions written in C work? Where can I learn about this? I find the source code itself rather overwhelming. I can see that trusty ol' dlopen() and friends is used on systems that support it but without any sense of the bigger picture it would take a long time to figure this out from the source code. An enormous amount could be written on this topic but as far as I can tell, almost nothing has been — the abundance of webpages describing the Python language itself makes this difficult to search
  • gdb 是如何工作的?(how does gdb work?)
    问题 我想知道 gdb 在内部是如何工作的。 例如,我知道一个简单的想法,它利用 ptrace() 系统调用来监视跟踪的程序。 但我想知道它是如何处理信号的,它如何插入新代码,以及它所做的其他如此美妙的事情。 回答1 查看 GDB 内部手册,其中涵盖了一些重要方面。 本文档还有一个较旧的 PDF 版本。 从手册: 本文档记录了 GNU 调试器 gdb 的内部结构。 它包括对 gdb 的关键算法和操作的描述,以及使 gdb 适应特定主机和目标的机制。 回答2 取自 gdbint.pdf: 它可以作为硬件断点或软件断点来完成: 硬件断点有时可用作某些芯片的内置调试功能。 通常,这些通过具有可以存储断点地址的专用寄存器来工作。 如果 PC(程序计数器的简写)曾经匹配断点寄存器中的值,CPU 将引发异常并将其报告给 GDB。 另一种可能性是在使用模拟器时; 许多仿真器包括监视从处理器输出的地址线的电路,如果地址与断点的地址匹配,则强制它停止。 第三种可能是目标已经有能力以某种方式做断点; 例如,ROM 监视器可能会执行自己的软件断点。 因此,尽管这些并不是真正的硬件断点,但从 GDB 的角度来看,它们的工作方式相同; 软件断点需要 GDB 做更多的工作。 基本理论是,GDB 会用陷阱、非法除法或其他会导致异常的指令替换程序指令,然后当遇到它时,GDB 会接受异常并停止程序。
  • What is NoSQL, how does it work, and what benefits does it provide? [closed]
    Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 7 years ago. Improve this question I've been hearing things about NoSQL and that it may eventually become the replacement for SQL DB storage methods due to the fact that DB interaction is often a bottle neck for speed on the web. So I just have a few questions: What exactly is it? How does it work? Why would it be better than using a SQL Database? And how much better is it? Is the technology too