KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > object > dna > impl > UTF8ByteDataHolder


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.object.dna.impl;
5
6 import java.io.Serializable JavaDoc;
7 import java.io.UnsupportedEncodingException JavaDoc;
8 import java.util.Arrays JavaDoc;
9
10 /**
11  * Holds byte data for strings. The main purpose of this class is to simply hold the bytes data for a String (no sense
12  * turning actually into a String instance in L2)
13  * <p>
14  * The reason it is UTF8ByteDataHolder and not ByteDataHolder is that asString() assumes that the byte data is a valid
15  * UTF-8 encoded bytes and creates String as <code> new String(bytes, "UTF-8"); </code>
16  */

17 public class UTF8ByteDataHolder implements Serializable JavaDoc {
18
19   private final byte[] bytes;
20   private int hash = 0;
21
22   // Used for tests
23
public UTF8ByteDataHolder(String JavaDoc str) {
24     try {
25       this.bytes = str.getBytes("UTF-8");
26     } catch (UnsupportedEncodingException JavaDoc e) {
27       throw new AssertionError JavaDoc(e);
28     }
29   }
30
31   public UTF8ByteDataHolder(byte[] b) {
32     this.bytes = b;
33   }
34
35   public byte[] getBytes() {
36     return bytes;
37   }
38
39   public String JavaDoc asString() {
40     try {
41       return new String JavaDoc(bytes, "UTF-8");
42     } catch (UnsupportedEncodingException JavaDoc e) {
43       throw new AssertionError JavaDoc(e);
44     }
45   }
46
47   public String JavaDoc toString() {
48     return asString();
49   }
50
51   public int hashCode() {
52     if (hash == 0) {
53       int tmp = 0;
54       for (int i = 0, n = bytes.length; i < n; i++) {
55         tmp = 31 * tmp + bytes[i++];
56       }
57       hash = tmp;
58     }
59     return hash;
60   }
61
62   public boolean equals(Object JavaDoc obj) {
63     if (obj instanceof UTF8ByteDataHolder) {
64       UTF8ByteDataHolder other = (UTF8ByteDataHolder) obj;
65       return ((Arrays.equals(this.bytes, other.bytes)) && this.getClass().equals(other.getClass()));
66     }
67     return false;
68   }
69 }
70
Popular Tags