Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

lab03-ready / project_solve / lab03 / src / avangard / demo / labs / lab03 / DemoContains

.java
Скачиваний:
18
Добавлен:
18.03.2015
Размер:
2.81 Кб
Скачать
package avangard.demo.labs.lab03;

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

/**
 * проверяем работу функция поиск и сортировки ...
 */
public class DemoContains {

	public static void main(String[] args) {
		try {
			final Pair<Long, String> value1 = new Pair<Long, String>(100000L, "Value1");
			final Pair<Long, String> value2 = new Pair<Long, String>(200L, "Value2");

			String id = "1";
			final Map<Object, Pair<Long, ?>> map = new HashMap<Object, Pair<Long, ?>>();
			map.put(value1.id, value1);
			map.put(value2.id, value2);

			System.out.println("== Testing use of Map and Set ==\n");

			System.out.println("\n* prepared Map: \n\t" + map);

			System.out.println("map.get('200'): " + map.get("200"));
			final long lval = 100000;
			System.out.println(String.format("map.get(long %s): %s", lval, map.get(lval)));
			System.out.println("map.get(value2.id): " + map.get(value2.id));

			final Set<Pair<Long, ?>> ss = new HashSet<Pair<Long, ?>>();
			ss.addAll(map.values());
			System.out.println("\n* prepared Set: \n\t" + ss);
			System.out.println("Set.contains('200'): " + ss.contains("200"));
			System.out.println("Set.contains(value1.id): " + ss.contains(value1.id));
			System.out.println("Set.contains(value2): " + ss.contains(value2));
		} catch (Throwable t) {
			t.printStackTrace(System.out);
		}
	}

	public static class Pair<TId extends Comparable, TValue> {

		final public TId id;
		final public TValue data;

		public Pair(TId id, TValue data) {
			this.id = id;
			this.data = data;
		}

		@Override
		public String toString() {
			return "Pair{" + "id " + id + ", '" + data + "'}";
		}

		@Override
		public int hashCode() {
			/*
			 int hash = 5;
			 hash = 47 * hash + Objects.hashCode(this.id);
			 return hash;return Objects.hashCode(this.id.toString());
			 */
			// return Objects.hashCode(this.id.toString());
			return this.id.hashCode();
		}

		@Override
		/**
		 * считаем что объекты равны по id
		 */
		public boolean equals(Object obj) {
			if (obj == null) {
				return false;
			}
			/*
			 // нестандартное сравнение: строки и числа сравниваем с id ...
			 if ( (obj.getClass() == String.class)
			 ||(obj.getClass() == Long.class)
			 ||(obj.getClass() == Integer.class)
			 ) {
			 return this.id.toString().compareTo(String.valueOf(obj));
			 }
			 */
			if (getClass() != obj.getClass()) {
				return false;
			}
			// this.data, other.data
			// if (!Objects.equals(this.data, other.data)) return false;
			final Pair<?, ?> other = (Pair<?, ?>) obj;
			return this.id.equals(other.id);
		}
	}

}
Соседние файлы в папке lab03