fork download
  1.  
  2. class KusoString {
  3. public KusoString(String text) {
  4. this.text = text;
  5. this.hashValue = this.hashCode();
  6. }
  7.  
  8. private final int hashValue;
  9. private final String text;
  10.  
  11. @Override
  12. public boolean equals(Object arg0) {
  13. if ( arg0 == null || !(arg0 instanceof KusoString) )
  14. return false;
  15. KusoString other = (KusoString)arg0;
  16.  
  17. if ( this.hashValue != 0 && other.hashValue != 0 && this.hashValue != other.hashValue )
  18. return false;
  19.  
  20. if ( this.text == null && other.text == null )
  21. return true;
  22. if ( this.text == null && other.text != null )
  23. return false;
  24. if ( this.text != null && other.text == null )
  25. return false;
  26.  
  27. assert this.text != null && other.text != null;
  28. if ( this.text.length() != other.text.length() )
  29. return false;
  30.  
  31. for ( int i = 0; i < this.text.length(); i++ ) {
  32. if ( this.text.charAt(i) != other.text.charAt(i) )
  33. return false;
  34. }
  35.  
  36. return true;
  37. }
  38.  
  39. @Override
  40. public int hashCode() {
  41. return this.text.hashCode();
  42. }
  43. }
  44.  
  45. class Program {
  46. public static void main(String[] args) throws Exception {
  47. StringBuilder sb = new StringBuilder();
  48. for ( int i = 0; i < 256 * 1024; i++ )
  49. sb.append('a');
  50. KusoString t1 = new KusoString(sb.toString() + '1');
  51. KusoString t2 = new KusoString(sb.toString() + '1');
  52. KusoString t3 = new KusoString(sb.toString() + '2');
  53. System.out.printf("%s\n", t1.equals(t2));
  54.  
  55. System.out.printf("ちょっとテスト\n");
  56. test(t1, t2);
  57.  
  58. System.out.printf("全比較したとき\n");
  59. test(t1, t2);
  60. System.out.printf("ハッシュ比較で済んだとき\n");
  61. test(t1, t3);
  62. }
  63.  
  64. private static void test(KusoString t1, KusoString t2) {
  65. final int N = 1000 * 1;
  66. long ts = System.currentTimeMillis();
  67.  
  68. boolean b = false;
  69. for ( int i = 0; i < N; i++ )
  70. b |= t1.equals(t2);
  71.  
  72. long te = System.currentTimeMillis();
  73. System.out.printf(" %.1fus\n", (double)(te - ts) / N * 1000, b);
  74. }
  75. }
  76.  
  77.  
Success #stdin #stdout 2.07s 380352KB
stdin
Standard input is empty
stdout
true
ちょっとテスト
    980.0us
全比較したとき
    979.0us
ハッシュ比較で済んだとき
    0.0us