You are on page 1of 36

Class doesn't override equals in superclass

FindBugs

1.0 cantellow 2011-5-24
1.1 2011-6-9

Pattern id Ctrl + F

Findbugs

1. EC_UNRELATED_TYPES

Bug: Call to equals() comparing different types


Pattern id: EC_UNRELATED_TYPES, type: EC, category: CORRECTNESS

equals equals object ==
equals instanceof

str.toString()

2. IM_BAD_CHECK_FOR_ODD

Bug: Check for oddness that won't work for negative numbers
Pattern id: IM_BAD_CHECK_FOR_ODD, type: IM, category: STYLE

row row % 2 == -1

x & 1 == 1 x % 2 != 0
3. NP_ALWAYS_NULL
Pattern: Null pointer dereference
id: NP_ALWAYS_NULL, type: NP, category: CORRECTNESS

A null pointer is dereferenced here. This will lead to a


NullPointerException when the code is executed.

4. RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE

Bug: Redundant nullcheck of bean1, which is known to be non-null


Pattern id: RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE, type: RCN,
category: STYLE

This method contains a redundant check of a known non-null value against


the constant null.

5. SS_SHOULD_BE_STATIC
Bug: Unread field: ADDRESS_KEY; should this field be static?
Pattern id: SS_SHOULD_BE_STATIC, type: SS, category: PERFORMANCE

This class contains an instance final field that is initialized to a


compile-time static value. Consider making the field static.

final
final

static

6. EQ_COMPARETO_USE_OBJECT_EQUALS

Bug: RsInterface defines compareTo(Object) and uses Object.equals()


Pattern id: EQ_COMPARETO_USE_OBJECT_EQUALS, type: Eq, category: BAD_PRACTICE

instanceof classcastexception
BUG (x.compareTo(y)==0) == (x.equals(y))
return 0 equals true PriorityQueue.remove 1.5
compareTo 1.6 equals

return 0 equals true

7. NM_METHOD_NAMING_CONVENTION

Bug: The method name MsmPlanDAOTest.TestViewMsmPlanList() doesn't start


with a lower case letter
Pattern id: NM_METHOD_NAMING_CONVENTION, type: Nm, category:
BAD_PRACTICE

Methods should be verbs, in mixed case with the first letter lowercase,
with the first letter of each internal word capitalized.

8. HE_EQUALS_USE_HASHCODE
Bug: PerfmSingleGraphPanel$RSCategory defines equals and uses Object.hashCode()
Pattern id: HE_EQUALS_USE_HASHCODE, type: HE, category: BAD_PRACTICE

equals hashCode object hashCode


JDK object hashCode native

Equals hashcode hashcode equals


HashMap/HashTable

hashcode equals hashCode


?
equals
1.====
2. instanceof
3.
4. equals
5. equals

equals

HashMap/HashTable
hashcode

9. NM_CONFUSING
Bug: Confusing to have methods
xxx.SellerBrandServiceImpl.getAllGrantSellerBrandsByBrandId(long) and
xxx.DefaultSellerBrandManager.getALLGrantSellerBrandsByBrandId(long)
Pattern id: NM_CONFUSING, type: Nm, category: BAD_PRACTICE

The referenced methods have names that differ only by capitalization.

10. MF_CLASS_MASKS_FIELD

Bug: Field PDHSubCardInstanceDialogCommand.m_instance masks field in superclass


ViewNEProperity
Pattern id: MF_CLASS_MASKS_FIELD, type: MF, category: CORRECTNESS

This class defines a field with the same name as a visible instance field
in a superclass. This is confusing, and may indicate an error if methods
update or access one of the fields when they wanted the other.

m_instance

11. NM_CLASS_NAMING_CONVENTION
Bug: The class name crossConnectIndexCollecter doesn't start with an upper case letter

Pattern id: NM_CLASS_NAMING_CONVENTION, type: Nm, category: BAD_PRACTICE

12. RE_POSSIBLE_UNINTENDED_PATTERN

Bug: "." used for regular expression


Pattern id: RE_POSSIBLE_UNINTENDED_PATTERN, type: RE, category: CORRECTNESS

String split
. $ ^ {}[] ()
| * + ?\\

\\

13.IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OU
TER_METHOD

Bug: Ambiguous invocation of either an outer or inherited method JExtendDialog.onOK()


Pattern id: IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD, type: IA,
category: STYLE

TargetSetupDialog JExtendDialog
JExtendDialog onOK JExtendDialog
onOK onOK onOK
onOK
JExtendDialog onOK
JExtendDialog onOK onOK
this.onOK this

outclass.this
onOK super.onOK()

14. DM_FP_NUMBER_CTOR

Bug: Method
OnlineLicenseDAOTest.testUpdateOnlineLicenseByOnlineMerchantId()
invokes inefficient Double.valueOf(double) constructor; use
OnlineLicenseDAOTest.java:[line 81] instead
Pattern id: DM_FP_NUMBER_CTOR, type: Bx, category: PERFORMANCE

Using new Double(double) is guaranteed to always result in a new object


whereas Double.valueOf(double) allows caching of values to be done by the
compiler, class library, or JVM. Using of cached values avoids object
allocation and the code will be faster.
Unless the class must be compatible with JVMs predating Java 1.5, use
either autoboxing or the valueOf() method when creating instances of
Double and Float.

new Ddouble(double) Ddouble.valueOf(double)

Ddouble.valueOf

15. CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE

Bug:AlarmSoundManager$SoundProperty defines clone() but doesn't implement Cloneable


Pattern id: CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE, type: CN, category: BAD_PRACTICE

SoundProperty clone Cloneable

Cloneable

16. STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE
Bug: Call to method of static java.text.DateFormat
Pattern id: STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE, type: STCAL, category:
MT_CORRECTNESS

TIME_FORMAT DateFormat DateFormat

vector
Sun Bug #6231579 Sun Bug #6178997
DateFormatSimpleDateFormatCalendar

java private

vector

private get get

DateFormat sun

17. SE_NO_SERIALVERSIONID

Bug: WindowHandlerManager$MySingleSelectionModel is Serializable; consider declaring a


serialVersionUID
Pattern id: SE_NO_SERIALVERSIONID, type: SnVI, category: BAD_PRACTICE
This class implements the Serializable interface, but does not define a
serialVersionUID field. A change as simple as adding a reference to
a .class object will add synthetic fields to the class, which will
unfortunately change the implicit serialVersionUID (e.g., adding a
reference to String.class will generate a static field
class$java$lang$String). Also, different source code to bytecode
compilers may use different naming conventions for synthetic variables
generated for references to class objects or inner classes. To ensure
interoperability of Serializable across versions, consider adding an
explicit serialVersionUID.

Serializable serialVersionUID

serialVersionUID
1.
2.

JFrame

serialVersionUID

18.SE_COMPARATOR_SHOULD_BE_SERIALIZABLE

Bug: ToStringComparator implements Comparator but not Serializable


Pattern id: SE_COMPARATOR_SHOULD_BE_SERIALIZABLE, type: Se, category: BAD_PRACTICE

ToStringComparator Comparator Serializable TreeMap


Serializable Serializable

Serializable serialVersionUID

19. ES_COMPARING_STRINGS_WITH_EQ
Bug: Comparison of String objects using == or !=
Pattern id: ES_COMPARING_STRINGS_WITH_EQ, type: ES, category: BAD_PRACTICE

string
FX String s = new String("xyz");
String

Object StringBuilder toString new String()


String name = ;OK class
String. Intern
==!=
= =!

equals

20. ES_COMPARING_STRINGS_WITH_EQ

Bug: Comparison of String parameter using == or !=


Pattern id: ES_COMPARING_PARAMETER_STRING_WITH_EQ, type: ES, category: BAD_PRACTICE

propertyName ==

equals

21. IM_AVERAGE_COMPUTATION_COULD_OVERFLOW
Bug: Computation of average could overflow
Pattern id: IM_AVERAGE_COMPUTATION_COULD_OVERFLOW, type: IM, category: STYLE

Findbugs (low+high)/2 int

Joshua Blochgoogle java widely publicized the bug pattern


.

use (low+high) >>> 1

22. SC_START_IN_CTOR

Bug: new AsyncCentral() invokes AsyncCentral$FireThread.start()


Pattern id: SC_START_IN_CTOR, type: SC, category: MT_CORRECTNESS

1. new <init>
JVM

2.

3. synchronized(:JLS 8.8.3 Constructor
Modifiers) synchronized
synchronized synchronized
<init>
new JVM

AsyncCentral FireThread AsyncCentral
AsyncCentral
FireThread AsyncCentral
AsyncCentral <init>
FireThread
AsyncCentral

Java.Concurrency.in.Practice
this FireThread this
this <init> FireThread

init

23. EQ_SELF_USE_OBJECT

Bug: ManageItem defines equals(ManageItem) method and uses Object.equals(Object)


Pattern id: EQ_SELF_USE_OBJECT, type: Eq, category: CORRECTNESS

ManageItem
Object boolean equals(Object)

@Override
JDK1.5 @Override JDK1.6
@Override

24.DLS_DEAD_LOCAL_STORE

Bug: Dead store to date


Pattern id: DLS_DEAD_LOCAL_STORE, type: DLS, category: STYLE

By the way
class
eclipse Preferences

IntegralItemDO integralItem = new IntegralItemDO();

25.FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER
Bug: Doomed test for equality to NaN
Pattern id: FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER, type: FE, category: CORRECTNESS

Findbugs
Nan
x == Double.NaN false

x Double.isNaN(x)

26. FI_EMPTY

Bug: FilterIPConfigDialog.finalize() is empty and should be deleted


Pattern id: FI_EMPTY, type: FI, category: BAD_PRACTICE

finalize
JDK finalize() Java JVM
finalize()

finalize

27.REC_CATCH_EXCEPTION
Bug: Exception is caught when Exception is not thrown
Pattern id: REC_CATCH_EXCEPTION, type: REC, category: STYLE

catch (Exception e) Findbugs


try catch RuntimeException

JVM RuntimeException
Exception EDT catch
(Exception e) RuntimeException

RuntimeException

for RuntimeException continue

28. DM_GC
Bug: DBExportTask2.exportDBRecords(DBExportProperty, String) forces garbage collection;
extremely dubious except in benchmarking code
Pattern id: DM_GC, type: Dm, category: PERFORMANCE

1. System.gc()JVM
2. System.gc() Full GC
GC Scavenge GC Full GCScavenge GC Eden
GCPerGen Eden
Scavenge GC GC Full GC Full GC
YoungTenured Perm Scavenge GC
Full GC

System.gc()

28. DP_DO_INSIDE_DO_PRIVILEGED

Bug: com.taobao.sellerservice.core.test.BaseTestJunit.autoSetBean() invokes


reflect.Field.setAccessible(boolean), which should be invoked from within a
doPrivileged block
Pattern id: DP_DO_INSIDE_DO_PRIVILEGED, type: DP, category: BAD_PRACTICE
This code invokes a method that requires a security permission check. If this code
will be granted security permissions, but might be invoked by code that does not
have security permissions, then the invocation needs to occur inside a doPrivileged
block.

doPrivileged

30. MS_SHOULD_BE_FINAL

Bug: IPv4Document.m_strInitString isn't final but should be


Pattern id: MS_SHOULD_BE_FINAL, type: MS, category: MALICIOUS_CODE

public protected final

public get

final

31. NM_FIELD_NAMING_CONVENTION

Bug: The field name TopoControlPaneII.SyncSelection doesn't start with a lower case letter
Pattern id: NM_FIELD_NAMING_CONVENTION, type: Nm, category: BAD_PRACTICE

sun
Bug: Field only ever set to null: RaisecomStatus.infoURL
Pattern id: UWF_NULL_FIELD, type: UwF, category: CORRECTNESS

infoURL null

32. MS_PKGPROTECT

Bug: ActionPatternManager.m_This should be package protected


Pattern id: MS_PKGPROTECT, type: MS, category: MALICIOUS_CODE

Findbugs m_oThis protected


public
protected

private
UserManager m_oThis = new UserManager();
Findbugs

protected private

33. FI_USELESS

Pattern: Finalizer does nothing but call superclass finalizer


id: FI_USELESS, type: FI, category: BAD_PRACTICE

finalize() Java finalize Object finalize

finalize()

34. NP_NULL_ON_SOME_PATH

Bug: Possible null pointer dereference of busCatId


Pattern id: NP_NULL_ON_SOME_PATH, type: NP, category: CORRECTNESS
There is a branch of statement that, if executed, guarantees that a null
value will be dereferenced, which would generate a NullPointerException
when the code is executed. Of course, the problem might be that the branch
or statement is infeasible and that the null pointer exception can't ever
be executed; deciding that is beyond the ability of FindBugs.

busCatId

35. NP_NULL_ON_SOME_PATH

Bug:.HierarchicalManagerImpl.isExistByName(String, long) forgets to


throw new exception.HierarchicalServiceException(String, Throwable)
Pattern id: RV_EXCEPTION_NOT_THROWN, type: RV, category: CORRECTNESS

This code creates an exception (or error) object, but doesn't do anything
with it. For example, something like

if (x < 0)
new IllegalArgumentException("x must be nonnegative");

It was probably the intent of the programmer to throw the created


exception:

if (x < 0)
throw new IllegalArgumentException("x must be nonnegative");

36. FI_FINALIZER_NULLS_FIELDS

Bug: CustomerResTreeDialog.java:[line 67] is set to null inside finalize method


Pattern id: FI_FINALIZER_NULLS_FIELDS, type: FI, category: BAD_PRACTICE

finalize m_UniResTree = null

finalize()

37. FI_PUBLIC_SHOULD_BE_PROTECTED

Bug: FilterIPConfigDialog.finalize() is public; should be protected


Pattern id: FI_PUBLIC_SHOULD_BE_PROTECTED, type: FI, category: MALICIOUS_CODE

Finalize protected public finalize

finalize()

38. IS2_INCONSISTENT_SYNC
Bug: Inconsistent synchronization of URLAlarmMonitor.m_Counter; locked 50% of time
Pattern id: IS2_INCONSISTENT_SYNC, type: IS, category: MT_CORRECTNESS

m_Counter 50% read


final
read write get set
set

get set

39. LI_LAZY_INIT_UPDATE_STATIC

Bug: Incorrect lazy initialization and update of static field MonitorRuleManager.m_This


Pattern id: LI_LAZY_INIT_UPDATE_STATIC, type: LI, category: MT_CORRECTNESS

m_This protected 1
initMonitorRules 2 getInstance m_This
m_This 1 initMonitorRules
2
BUG

initMonitorRules

initMonitorRules
40. LI_LAZY_INIT_STATIC

Bug: Incorrect lazy initialization of static field TopoController.m_This


Pattern id: LI_LAZY_INIT_STATIC, type: LI, category: MT_CORRECTNESS

bug 1 if 2 2
if a 1 1 b

happen-before DCL

41. WMI_WRONG_MAP_ITERATOR

Bug: Method JTAMainFrame.initView(JFrame) makes inefficient use of keySet iterator instead of


entrySet iterator
Pattern id: WMI_WRONG_MAP_ITERATOR, type: WMI, category: PERFORMANCE
This method accesses the value of a Map entry, using a key that was
retrieved from a keySet iterator. It is more efficient to use an iterator
on the entrySet of the map, to avoid the Map.get(key) lookup.

Map key key


value entry entry value
1.5:1
HashMap.get
1. public V get(Object key) {
2. if (key == null)
3. return getForNullKey();
4. int hash = hash(key.hashCode());
5. for (Entry<K,V> e = table[indexFor(hash, table.length)];
6. e != null;
7. e = e.next) {
8. Object k;
9. if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
10. return e.value;
11. }
12. return null;
13. }

value hashcode entry


hashcode for equals CPU CPU
map CPU

1. for (Map.Entry<String, JMenu> entry : menuList.entrySet()) {


2. mb.add(entry.getValue());

for(Map.Entry<String, List<BlackListDO>> tempEntiy:


companyBlackItemsMap.entrySet()) {
String key = tempEntiy.getKey();
List<BlackListDO> eachCompanyBlackItems = tempEntiy.getValue();

42. BC_VACUOUS_INSTANCEOF

Bug: instanceof will always return true, since all TopoTreeNode are instances of TopoTreeNode
Pattern id: BC_VACUOUS_INSTANCEOF, type: BC, category: STYLE

getSelectedTreeNode TopoTreeNode if instanceof


true null

instanceof

43. INT_BAD_REM_BY_1

Bug: Integer remainder modulo 1 computed


Pattern id: INT_BAD_REM_BY_1, type: INT, category: STYLE

I % 1 0I / 1 i

Bug: Load of known null value


Pattern id: NP_LOAD_OF_KNOWN_NULL_VALUE, type: NP, category: STYLE

The variable referenced at this point is known to be null due to an earlier


check against null. Although this is valid, it might be a mistake (perhaps
you intended to refer to a different variable, or perhaps the earlier check
to see if the variable is null should have been a check to see if it was
nonnull).

Node null node null


isDeleteSingleObject false if
node != null

44. EI_EXPOSE_REP2

DO

Bug: SingleNePollConfigDialog.collectValues(Hashtable) may expose internal representation by


storing an externally mutable object into SingleNePollConfigDialog.values
Pattern id: EI_EXPOSE_REP2, type: EI2, category: MALICIOUS_CODE

values this.values
values this.values

values this.values

DO

Bug: SingleNePollConfigDialog.collectValues(Hashtable) may expose internal representation by


storing an externally mutable object into SingleNePollConfigDialog.values
Pattern id: EI_EXPOSE_REP2, type: EI2, category: MALICIOUS_CODE

This code stores a reference to an externally mutable object into the


internal representation of the object. If instances are accessed by
untrusted code, and unchecked changes to the mutable object would
compromise security or other important properties, you will need to do
something different. Storing a copy of the object is better approach in
many situations.

DO Date gmtCrate
set gmtCreate

DO


public Date getGmtCreate() {
return new Date(this.gmtCreate.getTime()); //
}

45. EI_EXPOSE_REP

Bug: temsLoader.getItemsWithPriority() may expose internal representation by returning


ItemsLoader.m_htItemsWithPriority
Pattern id: EI_EXPOSE_REP, type: EI, category: MALICIOUS_CODE

findBugs public
get

get
get

46. NP_NULL_PARAM_DEREF

Bug: Method call passes null for nonnull parameter of queryScriptData(ObjService)


Pattern id: NP_NULL_PARAM_DEREF, type: NP, category: CORRECTNESS

getAllListFiles checked unchecked


allFiles null
queryScriptData null

queryScriptData

46. SBSC_USE_STRINGBUFFER_CONCATENATION

Bug: Method InitDBPoolParaTask.execute() concatenates strings using + in a loop


Pattern id: SBSC_USE_STRINGBUFFER_CONCATENATION, type: SBSC, category: PERFORMANCE

The method seems to be building a String using concatenation in a loop.


In each iteration, the String is converted to a
StringBuffer/StringBuilder, appended to, and converted back to a String.
This can lead to a cost quadratic in the number of iterations, as the
growing string is recopied in each iteration.

Better performance can be obtained by using a StringBuffer (or


StringBuilder in Java 1.5) explicitly.

+ string java

StringBuffer StringBuilder
47. RV_RETURN_VALUE_IGNORED_BAD_PRACTICE

Bug: NewScriptAction.actionPerformed(ActionEvent) ignores exceptional return value of


java.io.File.delete()
Pattern id: RV_RETURN_VALUE_IGNORED_BAD_PRACTICE, type: RV, category: BAD_PRACTICE

boolean
login int
0 1
use case
C
java checked Exception
java
File.delete

48. RV_RETURN_VALUE_IGNORED

Bug: BackupFileListPanel$PopupListener.maybeShowPopup(MouseEvent) ignores return value of


String.trim()
Pattern id: RV_RETURN_VALUE_IGNORED, type: RV, category: CORRECTNESS

String String String String


class s.trim
s

S = s.trim

49. DM_BOOLEAN_CTOR
Bug: TopoCardManagerAction.processLocalCard(Hashtable) invokes inefficient Boolean
constructor; use Boolean.valueOf(...) instead
Pattern id: DM_BOOLEAN_CTOR, type: Dm, category: PERFORMANCE

Boolean Boolean.valueOf Boolean.FALSE


Boolean.TRUE
API public Boolean(boolean value)
valueOf(boolean)

Boolean.valueOf Boolean.FALSE Boolean.TRUE

50. RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE
Pattern id: RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE,

StringBuffer StringBuffer

51. DM_NUMBER_CTOR

new Integer(int) Integer.valueOf(int)

bug

[Bx] Method invokes inefficient Number constructor; use static valueOf instead
[DM_NUMBER_CTOR]

Using new Integer(int) is guaranteed to always result in a new object


whereas Integer.valueOf(int) allows caching of values to be done by the compiler, class library,
or JVM. Using of cached values avoids object allocation and the code will be faster.

[]http://www.cnblogs.com/hyddd/articles/1391318.html
FindBugs Integer.ValueOf(int) new Integer(int) int
-128127 Integer.ValueOf(int) Integer(int) 3.5

JDK Integer.ValueOf(int)

public static Integer valueOf(int i) {


final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}

private static class IntegerCache {


private IntegerCache(){}

static final Integer cache[] = new Integer[-(-128) + 127 + 1];


static {
for(int i = 0; i < cache.length; i++)
cache = new Integer(i - 128);
}
}

ValueOf -128127 256 (IntegerCache)


int
-128
127 ValueOf(int) IntegerCache

public static void main(String []args) {


Integer a = 100;
Integer b = 100;
System.out.println(a==b);

Integer c = new Integer(100);


Integer d = new Integer(100);
System.out.println(c==d);
}

true
false
java Integer a = 100; -> Integer a = Integer.valueOf(100); a b
Cache c d c d

public static void main(String args[]) throws Exception{


Integer a = 100;
Integer b = a;
a = a + 1; // a++;
System.out.println(a==b);
}

false

a (a=a+1 a++)a b 100


false

You might also like