2015-05-24 2 views
0

Что-то странное происходит со следующим фрагментом тестового кода Java. Это было написано с использованием Spring.Если условие не оценено правильно

ResourceType resourceType1 = new ResourceType(RESOURCE_TYPE_NAME); 
resourceType1 = resourceTypeService.addResourceType(resourceType1); 

ResourceType resourceType2 = new ResourceType(RESOURCE_TYPE_NAME_2); 
resourceType2 = resourceTypeService.addResourceType(resourceType2); 

List<ResourceType> all = resourceTypeService.getAll(); 
List<ResourceType> myObjects = new ArrayList<>(); 
for (ResourceType resourceType : all) { 
    if(resourceType.getId() == resourceType1.getId() 
      || resourceType.getId() == resourceType2.getId()){ 
     myObjects.add(resourceType); 
    } 
} 

assertTrue(myObjects.get(0).getId() == resourceType1.getId()); 

Когда я бегу, он возвращает IndexOutOfBounds на .get(0) вызова.

Это странно, потому что resourceType1 и resourceType2 имеют идентификаторы внутри списка all.

Это результат отладки кода:

тип ресурса 1 после вставки:

resourceType1 = {[email protected]} 
id = 179 

Тип ресурса 1 после вставки:

resourceType2 = {[email protected]} 
id = 180 

все после getAll()

all = {[email protected]} size = 37 
.......... 
35 = {[email protected]} 
    id = 179 
36 = {[email protected]} 
    id = 180 

Это были данные отладки.

Почему состояние if не выполнено?

Update # 1

Ошибки StackTrace:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 
    at java.util.ArrayList.rangeCheck(ArrayList.java:653) 
    at java.util.ArrayList.get(ArrayList.java:429) 
    at com.test.ihbs.service.ResourceTypeServiceTest.test_getAll(xxx.java:107) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:497) 
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) 
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) 
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73) 
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) 
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73) 
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) 
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) 
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) 
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) 
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) 
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) 
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) 
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) 
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86) 
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49) 
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:64) 
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:497) 
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) 
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) 
    at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32) 
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) 
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source) 
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:106) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:497) 
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) 
    at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) 
    at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360) 
    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 
    at java.lang.Thread.run(Thread.java:745) 
+1

Каким типом данных является ID в ResourceType? – dunni

+2

Какой тип 'getId()' return? – Radiodef

+0

Тип возврата - 'long', но отладчик показывает' Long'. – tzortzik

ответ

3

Как я сказал в комментариях и не может сравнить Long с помощью == компаратора. Он работает только для значений между (-128, 127) и только если они не созданы с использованием нового ключевого слова. Он работает, потому что эти значения кэшируются JVM, поэтому сравнение ссылки возвращает true.

Посмотрите здесь Java: Integer equals vs. == или здесь https://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching

1)

Integer i = 100; 
Integer p = 100; 
if (i == p) System.out.println("i and p are the same."); 
if(i.equals(p)) System.out.println("i and p contain the same value."); 

Выход:

i and p are the same. 
i and p contain the same value. 

2)

Integer i = 200; 
Integer p = 200; 
if (i == p) System.out.println("i and p are the same."); 
if(i.equals(p)) System.out.println("i and p contain the same value."); 

Выход:

i and p contain the same value. 

3)

Integer i = new Integer (100); 
Integer p = new Integer(100); 
if(i==p) System.out.println(“i and p are the same object”); 
if(i.equals(p)) System.out.println(“ i and p contain the same value”); 

В таком случае, выход только:

i and p contain the same value 
+1

* "Он работает только для значений между (-128, 127)" * - и создается не с помощью ключевого слова 'new'. –

+0

Это относится и к Лонгу тоже? – tzortzik

+0

Я нашел ответ на ваших страницах. Благодаря! – tzortzik

0

"==" всегда сравнивают ячейку памяти или ссылки на объекты из ценности. метод equals всегда сравнивает значения. Но равно также косвенно использует оператор «==» для сравнения значений. Integer использует Integer cache для хранения значений от -128 до +127.If == оператор используется для проверки любых значений от -128 до 127, тогда он возвращает true.иначе, чем эти значения, он возвращает false.

Refer the link для получения дополнительной информации.

Смежные вопросы