Java tutorial
//package com.java2s; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; public class Main { /** * Finds an item by iterating through the specified iterator. * * @param item the object to find * @param iter the iterator to examine * @return list index of the item or -1 if the item was not found */ public static int findObject(Object item, ListIterator<?> iter) { while (iter.hasNext()) { Object o = iter.next(); if (item == null ? o == null : item.equals(o)) { return iter.previousIndex(); } } return -1; } /** * Implements <em>equals</em> per the contract defined by {@link List#equals(Object)}. * * @param list the list * @param o an object to compare to the list * @return true if {@code o} equals {@code list} */ public static boolean equals(List<?> list, Object o) { if (!(o instanceof List)) { return false; } if (list == o) { return true; } List<?> l = (List<?>) o; if (l.size() != list.size()) { return false; } return listContentsEquals(list, l); } /** * Implements <em>equals</em> per the contract defined by {@link Set#equals(Object)}. * * @param set the set * @param o an object to compare to the list * @return true if {@code o} equals {@code list} */ public static boolean equals(Set<?> set, Object o) { if (!(o instanceof Set)) { return false; } if (set == o) { return true; } Set<?> other = (Set<?>) o; if (set.size() != other.size()) { return false; } // The spec for interface Set says a set should never contain itself, but most implementations // do not explicitly block this. So the paranoid code below handles this case. boolean containsItself = false; for (Object element : set) { if (element == set || element == other) { // don't test using contains(...) since that could cause infinite recursion containsItself = true; } else { if (!other.contains(element)) { return false; } } } if (containsItself) { // safely check that other also contains itself for (Object element : other) { if (element == set || element == other) { return true; } } return false; } return true; } private static boolean listContentsEquals(Iterable<?> l1, Iterable<?> l2) { Iterator<?> iter1 = l1.iterator(); Iterator<?> iter2 = l2.iterator(); while (iter1.hasNext()) { if (!iter2.hasNext()) { return false; } Object e1 = iter1.next(); Object e2 = iter2.next(); if ((e1 == l1 && (e2 == l1 || e2 == l2)) || (e1 == l2 && (e2 == l1 || e2 == l2))) { // handle case where list contains itself - don't overflow stack continue; } if (e1 == null ? e2 != null : !e1.equals(e2)) { return false; } } if (iter2.hasNext()) { return false; } return true; } public static boolean contains(Iterator<?> iteratorToCheck, Object item) { while (iteratorToCheck.hasNext()) { Object o = iteratorToCheck.next(); if (o == null ? item == null : o.equals(item)) { return true; } } return false; } }