Resumo Effective Java - Parte 2 (Métodos comuns a todos os objetos)  
Autor: Masdeval | Publicado: 2013-03-20T07:34:00-07:00

<!--[if !mso]>

v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}

<![endif]-->
<!--[if gte mso 9]>
 
  Normal
  0
  false
  
  21
  
  
  false
  false
  false
  
  PT-BR
  X-NONE
  X-NONE
  
   
   
   
   
   
   
   
   
   
  
  
  
   
   
   
   
   
   
   
   
   
   
   
  
<![endif]--><!--[if gte mso 9]>
 <w:LatentStyles DefLockedState="false" DefUnhideWhenUsed="true"
  DefSemiHidden="true" DefQFormat="false" DefPriority="99"
  LatentStyleCount="267">
  <w:LsdException Locked="false" Priority="0" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Normal"/>
  <w:LsdException Locked="false" Priority="9" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="heading 1"/>
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  <w:LsdException Locked="false" Priority="10" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Title"/>
  
  <w:LsdException Locked="false" Priority="11" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Subtitle"/>
  <w:LsdException Locked="false" Priority="22" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Strong"/>
  <w:LsdException Locked="false" Priority="20" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Emphasis"/>
  <w:LsdException Locked="false" Priority="59" SemiHidden="false"
   UnhideWhenUsed="false" Name="Table Grid"/>
  
  <w:LsdException Locked="false" Priority="1" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="No Spacing"/>
  <w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading"/>
  <w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List"/>
  <w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid"/>
  <w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1"/>
  <w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2"/>
  <w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1"/>
  <w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2"/>
  <w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1"/>
  <w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2"/>
  <w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3"/>
  <w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List"/>
  <w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading"/>
  <w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List"/>
  <w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid"/>
  <w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 1"/>
  <w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 1"/>
  <w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 1"/>
  <w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 1"/>
  <w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 1"/>
  <w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 1"/>
  
  <w:LsdException Locked="false" Priority="0" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="List Paragraph"/>
  <w:LsdException Locked="false" Priority="29" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Quote"/>
  <w:LsdException Locked="false" Priority="30" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Intense Quote"/>
  <w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 1"/>
  <w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 1"/>
  <w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 1"/>
  <w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 1"/>
  <w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 1"/>
  <w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 1"/>
  <w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 1"/>
  <w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 1"/>
  <w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 2"/>
  <w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 2"/>
  <w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 2"/>
  <w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 2"/>
  <w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 2"/>
  <w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 2"/>
  <w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 2"/>
  <w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 2"/>
  <w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 2"/>
  <w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 2"/>
  <w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 2"/>
  <w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 2"/>
  <w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 2"/>
  <w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 2"/>
  <w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 3"/>
  <w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 3"/>
  <w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 3"/>
  <w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 3"/>
  <w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 3"/>
  <w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 3"/>
  <w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 3"/>
  <w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 3"/>
  <w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 3"/>
  <w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 3"/>
  <w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 3"/>
  <w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 3"/>
  <w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 3"/>
  <w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 3"/>
  <w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 4"/>
  <w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 4"/>
  <w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 4"/>
  <w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 4"/>
  <w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 4"/>
  <w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 4"/>
  <w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 4"/>
  <w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 4"/>
  <w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 4"/>
  <w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 4"/>
  <w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 4"/>
  <w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 4"/>
  <w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 4"/>
  <w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 4"/>
  <w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 5"/>
  <w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 5"/>
  <w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 5"/>
  <w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 5"/>
  <w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 5"/>
  <w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 5"/>
  <w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 5"/>
  <w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 5"/>
  <w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 5"/>
  <w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 5"/>
  <w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 5"/>
  <w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 5"/>
  <w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 5"/>
  <w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 5"/>
  <w:LsdException Locked="false" Priority="60" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Shading Accent 6"/>
  <w:LsdException Locked="false" Priority="61" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light List Accent 6"/>
  <w:LsdException Locked="false" Priority="62" SemiHidden="false"
   UnhideWhenUsed="false" Name="Light Grid Accent 6"/>
  <w:LsdException Locked="false" Priority="63" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 1 Accent 6"/>
  <w:LsdException Locked="false" Priority="64" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Shading 2 Accent 6"/>
  <w:LsdException Locked="false" Priority="65" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 1 Accent 6"/>
  <w:LsdException Locked="false" Priority="66" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium List 2 Accent 6"/>
  <w:LsdException Locked="false" Priority="67" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 1 Accent 6"/>
  <w:LsdException Locked="false" Priority="68" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 2 Accent 6"/>
  <w:LsdException Locked="false" Priority="69" SemiHidden="false"
   UnhideWhenUsed="false" Name="Medium Grid 3 Accent 6"/>
  <w:LsdException Locked="false" Priority="70" SemiHidden="false"
   UnhideWhenUsed="false" Name="Dark List Accent 6"/>
  <w:LsdException Locked="false" Priority="71" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Shading Accent 6"/>
  <w:LsdException Locked="false" Priority="72" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful List Accent 6"/>
  <w:LsdException Locked="false" Priority="73" SemiHidden="false"
   UnhideWhenUsed="false" Name="Colorful Grid Accent 6"/>
  <w:LsdException Locked="false" Priority="19" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Subtle Emphasis"/>
  <w:LsdException Locked="false" Priority="21" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Intense Emphasis"/>
  <w:LsdException Locked="false" Priority="31" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Subtle Reference"/>
  <w:LsdException Locked="false" Priority="32" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Intense Reference"/>
  <w:LsdException Locked="false" Priority="33" SemiHidden="false"
   UnhideWhenUsed="false" QFormat="true" Name="Book Title"/>
  
  
 
<![endif]--><!--[if gte mso 10]>

 /* Style Definitions */
 table.MsoNormalTable
 {mso-style-name:"Tabela normal";
 mso-tstyle-rowband-size:0;
 mso-tstyle-colband-size:0;
 mso-style-noshow:yes;
 mso-style-priority:99;
 mso-style-parent:"";
 mso-padding-alt:0in 5.4pt 0in 5.4pt;
 mso-para-margin:0in;
 mso-para-margin-bottom:.0001pt;
 text-align:justify;
 text-indent:8.5pt;
 mso-line-height-alt:5.0pt;
 mso-pagination:widow-orphan;
 text-autospace:ideograph-other;
 font-size:10.0pt;
 font-family:"Calibri","sans-serif";}

<![endif]--><!--[if gte mso 9]>
 
<![endif]--><!--[if gte mso 9]>
 
  
 <![endif]-->



Capítulo 3 – Métodos comuns a todos os objetos



Item 8 – Obedecendo o
contrato do equals



·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Sempre que instâncias de uma classe precisarem
ser comparadas entre si e houver a noção de identidade que difere da mera
identidade entre objetos (ou seja, aquela que retorna verdadeiro meramente se
dois objetos forem iguais na memória), o método equals deve ser
implementado.&nbsp; 

·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Deve-se obedecer as seguintes regras (contrato)
ao sobreescrever o equals:



o&nbsp;&nbsp;
Reflexividade: Dado x, x.equals(x) deve retornar
true.

o&nbsp;&nbsp;
Simetria: Dado x e y, x.equals(y) deve retornar
true se e somente se y.equals(x) retornar true.

o&nbsp;&nbsp; Transitividade:
Dado x,y e z. Se x.equals(y) é true e y.equals(z) é true, então x.equals(z)
deve ser true.



·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Transitividade: Essa característica merece uma
atenção especial. A discussão que segue é longa e complicada, mas achei
importante acrescentar aqui. 



Numa
relação de herança, nada impede que uma subclasse acrescente atributos que
devem ser considerados na execução do equals. Isso gera inúmeros problemas!
Vejamos o código abaixo:







 

  
  
  
  
 

  
  
  
   

    

public class Point {



&nbsp;
    private final int x;

&nbsp;
    private final int y;

&nbsp;
    public Point(int x, int y) {

this.x = x;

this.y = y;

}



@Override public boolean equals(Object o)
    {



&nbsp;
    if (!(o instanceof Point))

&nbsp;&nbsp;&nbsp;
    return false;



&nbsp;
    Point p = (Point)o;

&nbsp;
    return p.x == x &amp;&amp; p.y == y;

}



... // Remainder omitted

}




   

&nbsp;
 

  
  
  
  
   

    

public class ColorPoint extends Point {



private final Color color;



public ColorPoint(int x, int y, Color
    color) {



super(x, y);

this.color = color;



}

... // Remainder omitted

}




   

&nbsp;
 

  
 

&nbsp;





O funcionamento
que esperamos é que consigamos comparar intercaladamente pontos e pontos
coloridos através do método equals. Afinal, são todos pontos.&nbsp; Mas como ColorPoint acrescentou uma
informação a mais à sua identidade, esta deve ser considerada. Como implementar
o equals para a classe ColorPoint? Vejamos algumas soluções. 



1 - Comparar apenas objetos
da mesma classe: 



// Broken - violates symmetry!

@Override public boolean equals(Object o) {



if (!(o instanceof ColorPoint))

return false;



return super.equals(o)
&amp;&amp; ((ColorPoint) o).color == color;



}



Esse
código viola a simetria. Point.equals(ColorPoint) retornará true se as
coordenadas forem as mesmas mas ColorPoint.equals(Point) sempre retornará
false. 



2 – Não
considerar informação de cor em comparações misturadas



Resolve o
problema da simetria mas ao custo da transitividade



// Broken - violates transitivity!

@Override public boolean equals(Object o) {



if (!(o instanceof Point))

return false;

&nbsp;&nbsp;&nbsp;&nbsp; 

if (!(o instanceof ColorPoint))

return o.equals(this); //nao considera cor se Object for Point

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

return super.equals(o) &amp;&amp;
((ColorPoint) o).color == color;



}



ColorPoint p1 = new ColorPoint(1, 2,
Color.RED);

Point p2 = new Point(1, 2);

ColorPoint p3 = new ColorPoint(1, 2,
Color.BLUE);



P1.equals(P2) retorna true = &gt; chama o
equals do ColorPoint na linha “return o.equals(this)”



P2.equals(P3) retorna true =&gt; chama o
equals do Point



P1.equals(P3) retorna false =&gt; retorna
falso pois são ColorPoint de cores diferentes



3 – Usando o getClass&nbsp; ao invés do
instanceOf



// Broken - violates Liskov substitution
principl

@Override public boolean equals(Object o) {



&nbsp; if (o
== null || o.getClass() != getClass())

&nbsp;&nbsp;&nbsp;
return false;

&nbsp; Point
p = (Point) o;

&nbsp;
return p.x == x &amp;&amp; p.y == y;



}



O código
acima compara apenas objetos da mesma classe.&nbsp;
O princípio da substituição de
Liskov diz que qualquer propriedade importante para um tipo deve valer também
para o subtipo. Assim, qualquer método escrito para um tipo, deve funcionar
corretamente nos seus subtipos. A implementação do equals, na classe Point, na
forma acima, viola esta propriedade. Qualquer subclasse criada a partir de
Point e que precisar (e puder) usar o equals da classe Point, não vai
funcionar. Sempre que esta nova classe for comparada com a classe Point irá
retornar false, independentemente se a comparação dos atributos estiver
válida.&nbsp; 



Não há um meio satisfatório de estender uma
classe, adicionar um atributo e ainda a relação de identidade continuar
funcionando.

A melhor
solução para isso é: ao invés de fazer herança, optar por composição. Concluímos que, toda vez que uma classe é estendida e
um novo atributo adicionado, isso vai quebrar o método equals implementado na
superclasse. Quando uma comparação for feita entre um objeto da sub.equals(super), o método da
subclasse vai querer utilizar para comparação um atributo que só ela tem.



Evitamos isso utilizando
composição ao invés de herança:



// Adds a value component without violating the equals
contract

public class ColorPoint {



&nbsp;private final
Point point;

&nbsp;private final
Color color;



&nbsp;public
ColorPoint(int x, int y, Color color) {



&nbsp; if (color ==
null)

&nbsp;&nbsp; throw new
NullPointerException();

&nbsp; point = new Point(x, y);

&nbsp; this.color =
color;

&nbsp;}





@Override public boolean equals(Object o) {



&nbsp;if (!(o
instanceof ColorPoint))//Como herança não está envolvida, não é 

&nbsp; return false;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //preciso permitir a comparação de Point com

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //ColorPoint &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 



&nbsp;ColorPoint cp =
(ColorPoint) o;

&nbsp;return
cp.point.equals(point) &amp;&amp; cp.color.equals(color);

}

... // Remainder omitted



}


OBS.: Sempre comparar double com Double.compare e
float com Float.compare 





Item 9 – Hashcode



·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Algoritmo para gerar hashcode:



1.
Store some constant nonzero value, say, 17, in an int variable called result.

2. For
each significant field f in your object (each field taken into account by the
equals method, that is), do the following:



a.
Compute an int hash code c for the field:

i. If the field is a boolean, compute (f ? 1 : 0).

ii. If the field is a byte, char, short, or int, compute (int) f.

iii. If the field is a long, compute (int) (f ^ (f &gt;&gt;&gt; 32)).

iv. If the field is a float, compute Float.floatToIntBits(f).

v. If the field is a double, compute Double.doubleToLongBits(f), and

then hash the resulting long as in step 2.a.iii.

vi. If the field is an object reference and this class’s equals method
compares the field by recursively invoking equals, recursively invoke hashCode
on the field. If a more complex comparison is required, compute a “canonical
representation” for this field and invoke hashCode on the canonical
representation. If the value of the field is null, return 0 (or some other
constant, but 0 is traditional).

vii. If the field
is an array, treat it as if each element were a separate field. That is,
compute a hash code for each significant element by applying these rules
recursively, and combine these values per step 2.b. If every element in an
array field is significant, you can use one of the Arrays.hashCode methods
added in release 1.5.



b. Combine the hash code c computed in step 2.a into
result as follows: result = 31 * result
+ c;



3. Return result.



4. When you are finished writing the hashCode method,
ask yourself whether equal instances have equal hash codes. Write unit tests to
verify your intuition!



Ex:

//
Lazily initialized, cached hashCode

private
volatile int hashCode;&nbsp; // (See Item 71)



@Override
public int hashCode() {

&nbsp; int result = hashCode;

&nbsp; if (result == 0) {

&nbsp;&nbsp;&nbsp; result = 17;

&nbsp;&nbsp;&nbsp; result = 31 * result + areaCode;

&nbsp;&nbsp;&nbsp; result = 31 * result + prefix;

&nbsp;&nbsp;&nbsp; result = 31 * result + lineNumber;

&nbsp;&nbsp;&nbsp; hashCode = result;

&nbsp; }

&nbsp;return
result;

}



Item 13 – Classes e Interfaces



·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Atributos
devem ser PRIVADOS.

·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Uma
exceção pode ser as constantes. Campos public
static final SEMPRE devem apontar para primitivos ou objetos imutáveis. Se
não apontarem para objetos imutáveis, apesar da referencia não poder ser
alterada, o objeto poderá! Um array é sempre mutável e assim nunca deve ser
criado como constante. 

·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Exemplo
de como disponibilizar um array privado de forma que continue imutável:



private static final Thing[] PRIVATE_VALUES = { ... };

public static final
List VALUES = Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));



ou



private static final Thing[] PRIVATE_VALUES = { ... };

public static final Thing[] values() {&nbsp; return PRIVATE_VALUES.clone();&nbsp; }



Item 10 – Sempre sobreescreva toString

Item 11 – Sobreescreva o método clone com
cuidado

Item 12 – Considere implementar a
interface Comparable