Untitled

 avatar
Darin
plain_text
a year ago
1.9 kB
1
Indexable
Never
đây là đoạn code của tôi, hãy trả lời câu hỏi mà tôi yêu cầu:

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

class UserSolution {
	// chưa rõ String trong map là value hay field
	Map<String, Set<Record>> hashMap[] = new HashMap[5];

	void InitDB() {
		for (int i = 0; i < 5; i++)
			hashMap[i] = new HashMap<>();
	}

	void Add(String... fields) {
		Record record = new Record(fields);
		for (int i = 0; i < fields.length; i++)
			hashMap[i].computeIfAbsent(fields[i], k -> new HashSet<>()).add(
					record);
	}

	int Delete(int field, String str) {
		Set<Record> records = hashMap[field].getOrDefault(str, new HashSet<>());
		int size = records.size();
		for (Record record : new HashSet<>(records))
			for (int i = 0; i < 5; i++)
				hashMap[i].get(record.field[i]).remove(record);
		return size;
	}

	int Change(int field, String str, int changefield, String changestr) {
		Set<Record> records = hashMap[field].getOrDefault(str, new HashSet<>());
		int size = records.size();
		for (Record record : new HashSet<>(records)) {
			hashMap[changefield].get(record.field[changefield]).remove(record);
			record.field[changefield] = changestr;
			hashMap[changefield].computeIfAbsent(changestr,
					k -> new HashSet<>()).add(record);
		}
		return size;
	}

	Solution.Result Search(int field, String str, int returnfield) {
		Solution.Result result = new Solution.Result();
		Set<Record> records = hashMap[field].getOrDefault(str, new HashSet<>());
		result.count = records.size();
		if (records.size() == 1) {
			Record record = (Record) records.toArray()[0];
			result.str = record.field[returnfield];
		}
		return result;
	}
}

class Record {
	String field[];

	// nhận vào value
	Record(String... strings) {
		field = Arrays.copyOf(strings, strings.length);
	}
}