2013-07-22 3 views
0

에서 객체 저장소하면 다음과 같은 인터페이스와 간단한 객체 저장소를 고려
는 중복 제거 수집

// add an object with ‘blob’ content into the system and return an id 
int put(string blob); 

// retrieve the contents of an object identified by ‘id’. NULL if doesn’t exist 
string get(int); 

// delete an object identified by ‘id’ 
void delete(int id); 

//number of (non duplicate) objects stored in the object store 
int size(); 

요구 사항
객체 저장소가 해제 복제해야 객체. 동일한 바이트 순서가 두 번 저장되는 경우 저장소에 데이터를 두 번 저장하면 안됩니다. 객체 은 상당히 클 수 있습니다 (예 : 1K에서 5MB 사이의 크기). BLOB는 변경 불가능합니다 .. 우리는이 API 호출에서 표준 순차 일관성 의미론을 찾고 있습니다. 객체가 'put'되어있는 경우는 다음의 즉각적인 'get'호출 ( )은 이전에 put 된 값을 반환해야합니다. 예 : 클라이언트가 다음을 실행하는 경우 :

Id = objectstore.put(data); 
data1 = objectstore.get(id); 

두 번째 작업은 'data'가 가리키는 것과 동일한 바이트 시퀀스를 반환해야합니다. 다른 클라이언트/프로세스/스레드가 에 간섭 할 수 없어야합니다. 지금까지

내 코드 :

import java.util.HashMap; 
import java.util.HashSet; 
import java.util.Map; 
import java.util.Set; 

public class ObjectStore { 

String blobString; 
Object objectId; 

public ObjectStore(String blobString, Object objectId) { 

    this.blobString = blobString; 
    this.objectId = objectId; 
} 

@Override 
public boolean equals(Object o){ 

    if(!(o instanceof ObjectStore)){ 
     return false; 
    } 
    if((o == null) || (o.getClass() != this.getClass())) 
     return false; 
    // object must be Test at this point 
    ObjectStore store = (ObjectStore)o; 
    return blobString.toString() == store.blobString && 
     (objectId != null && objectId.equals(store.objectId)); 
} 

@Override 
public int hashCode() { 
    int hash = 7; 
    hash = 31 * hash + blobString.hashCode(); 
    hash = 31 * hash + ((objectId == null) ? 0 : objectId.hashCode()); 

    return hash; 
} 

Set<String> set = new HashSet<String>(); 

    /** 
    * Put object into store and return id. 
    * @param blobString 
    * @return 
    */ 
    public int put(String blobString) { 
     set.add(blobString); 
    return 0; 
    } 

    /** 
    * Get object corresponding to id. Return null if no such object exists. 
    * @param objectId 
    * @return 
    */ 
    public String get(int objectId) { 

    return null; 
    } 

    /** 
    * Release object - don't need it anymore. 
    * @param objectId 
    */ 
    public void delete(int objectId) { 
    // stub 
    } 

    /** 
    * Number of distinct blobs stored in the objectStore 
    * @return 
    */ 
    public int size() { 
    // stub 
    return 0; 
    } 

public static void main(String[] args) { 

    Map<String, Object> map = new HashMap<String, Object>(); 


} 

} 

나는 내가지도 나 설정 인터페이스 때문에 풋() 메소드의 리턴 객체 ID를 사용할 필요가 무엇이든지 식별 할 수없는입니다.

답변

0

개체를 정수 ID에 매핑 할 때 Map을 사용하십시오. 세트는 반드시 데이터를 맵핑하는 것은 아니며, 중복 요소가없는 콜렉션입니다.

그러나 인터페이스에 쓰는 것처럼 보이기 때문에 구현 내부는 중요하지 않습니다. 가장 잘 작동하는 것을 사용하고 인터페이스 요구 사항과 함께 작동합니다.

편집 2 :

나는이 구현 된 경우에, 나는 put 작업에 고유 ID를 생성하는 정수를 사용하십시오. 이것은 최대 약 4 억 put 개의 고유 한 ID를 제공합니다.

또한 일부 얼룩 시퀀스가 ​​전에 추가되었는지 확인하려면 두 번째 맵이 필요합니다. 이렇게하면 처음으로 같은 키를 사용하여 오래된 얼룩을 대체 할 수 있습니다.

int idProvider=0; 
HashMap<Integer, String> map1 = new HashMap<Integer, String>(); 
HashMap<String, Integer> map2 = new HashMap<String, Integer>(); 
public int put(String blob){ 
    int id = -1; 
    if(map2.containsKey(blob)){ 
     id = map2.get(blob); 
    }else{ 
     id = idProvider; 
     idProvider+=1; 
     map2.put(blob, id); 
    } 
    map1.put(id, blob); 
    return id; 
} 
public void delete(int id){ 
    String blob = map1.remove(id); 
    if(blob!=null){ 
     map2.remove(blob); 
    } 
} 
String get(int id){ 
    String blob = map1.get(id); 
    return blob; 
} 
int size(){ 
    return map1.size(); 
} 

스레드 안전이 문제가되지 않는 한 질문의 모든 기준을 충족해야합니다. 그렇다면 단지 액세스를 동기화하십시오. 나는이 코드를 컴파일하고 테스트했다.

테스트 :

ObjectStore store = new ObjectStore(); 
    int id1 = store.put("hello"); 
    int id2 = store.put("world"); 
    int id3 = store.put("world"); 
    if(store.size()!=2) 
     throw new RuntimeException("Wrong size"); 
    if (id2 != id3) 
     throw new RuntimeException("Ids not equal?"); 
    String strHello = store.get(id1); 
    String strWorld = store.get(id3); 
    if (!strHello.equals("hello") || !strWorld.equals("world")) 
     throw new RuntimeException(); 
    store.delete(id3); 
    String strShouldBeNull = store.get(id3); 
    if(strShouldBeNull!=null) 
     throw new RuntimeException(); 
+0

당신은 내가() 메소드를 넣어 구현할 방법 좀 도와 줄래? –

+0

물론, 저는 현재의 문제 설명을 풀 솔루션으로 포함시키기 위해 질문을 편집했습니다. 이것이 충분하다면 제 대답을 받아주십시오. 그렇지 않다면 알려주세요. –

+0

blob에서 값을 가져 오는 동안 hashCode() 메서드의 해시 값을 사용하여 중복 값을 무시할 수 있습니까? 나는 어떻게 반환 blob.hashCode() 같이 사용합니까 ??? –